JavaScript Archives - codingem.com https://www.codingem.com/category/javascript/ software development and tech. Thu, 10 Jul 2025 07:28:14 +0000 en-GB hourly 1 https://wordpress.org/?v=6.9.4 https://www.codingem.com/wp-content/uploads/2021/04/cropped-cropped-Logo_Codingem_blue_white-32x32.png JavaScript Archives - codingem.com https://www.codingem.com/category/javascript/ 32 32 How to Pass a Variable from HTML Page to Another (w/ JavaScript) https://www.codingem.com/javascript-pass-variable-from-html-page-to-another/ Thu, 16 Feb 2023 10:55:22 +0000 https://www.codingem.com/?p=13575 One way to pass a variable from one HTML page to another using JavaScript is to use the browser’s localStorage object. localStorage provides a way to store key-value pairs in the user’s web browser, so that they persist across different pages and sessions. Here’s an example of how you could use localStorage to pass a […]

The post How to Pass a Variable from HTML Page to Another (w/ JavaScript) appeared first on codingem.com.

]]>
One way to pass a variable from one HTML page to another using JavaScript is to use the browser’s localStorage object.

localStorage provides a way to store key-value pairs in the user’s web browser, so that they persist across different pages and sessions.

Here’s an example of how you could use localStorage to pass a variable between two HTML pages.

Page 1:

window.onload = function() {
   var value = prompt("Write a value here: ");
   localStorage.setItem("inputValue", value);
}

Page 2:

window.onload = alert(localStorage.getItem("inputValue"));

This code asks for a value from a user, stores it in a local database, and retrieves it on the other page.

I hope this quick answer helps.

If you’re having a hard time understanding what happens here or where you should add these scripts in the HTML, make sure to read the full example below.

Full Example (with Explanation)

Let’s take a look at a full example that better demonstrates how the idea of using localStorage to pass values between two HTML pages.

First of all, here’s my example project setup with two HTML pages in the same folder:

The task is to ask the user for a value on page1 and then pass the value to page2.

Here’s the HTML/JavaScript code that I’ve placed in the page1.html file:

<!DOCTYPE html>
<html>
  <head>
    <script>
      function submitValue() {
        // Get the value entered by the user
        var input = document.getElementById('value-input');
        var value = input.value;
        
        // Store the value in localStorage
        localStorage.setItem('myValue', value);
        
        // Redirect to the second page
        window.location.href = 'page2.html';
      }
    </script>
  </head>
  <body>
    <h1>Page 1</h1>
    <p>Enter a value:</p>
    <input type="text" id="value-input">
    <button onclick="submitValue()">Submit</button>
  </body>
</html>

This page asks the user for an input value and stores it in JavaScript’s local database called localStorage.

And here’s the code in the page2.html file:

<!DOCTYPE html>
<html>
  <head>
    <script>
      window.onload = function() {
        // Get the value from localStorage
        var value = localStorage.getItem('myValue');
        
        // Display the value on the page
        var output = document.getElementById('value-output');
        output.innerText = value;
      };
    </script>
  </head>
  <body>
    <h1>Page 2</h1>
    <p>The value you entered on the first page was:</p>
    <p id="value-output"></p>
  </body>
</html>

As soon as this page loads, it grabs the stored value from the local storage and shows it in the HTML content.

Opening the page1.html with your browser, you will see a view like this:

Enter some text into the input field and press “Submit”.

This action opens up the page2.html with your browser and you’ll see a view like this:

As you can see, the name “Alice” carried over from page1.html to page2.html.

In reality, though, the value was never passed between the two pages. Instead, it was stored in the localStorage which all the HTML pages have access.

What Is localStorage?

localStorage is a feature in JavaScript that allows you to store key-value pairs in the browser’s local storage. This means that you can store data in the browser that will persist even after the user closes the browser or navigates to a different web page.

The localStorage object provides a simple interface for working with the browser’s local storage.

It has methods for setting, getting, and removing key-value pairs, as well as for clearing all of the data stored in the local storage.

Here are some examples of how to use localStorage:

1. Setting a value:

localStorage.setItem('myKey', 'myValue');

This code sets the value of the myKey key to myValue into the localStorage object. Any page can now go and grab this value with the key myKey.

2. Obtaining a value:

var value = localStorage.getItem('myKey');

This code retrieves the value of the myKey key and stores it in the value variable.

3. Removing a value:

localStorage.removeItem('myKey');

This code removes the key-value pair with the myKey key from the local storage.

4. Clearing all data:

localStorage.clear();

This code removes all of the data stored in the local storage.

Note that localStorage can only store strings.

If you need to store more complex data types, such as arrays or objects, you can use the JSON.stringify() and JSON.parse() methods to convert them to and from strings, respectively.

So for example, if you want to carry an array from one HTML page to another, you can’t just store the array in localStorage as is. Instead, you need to convert it to a string like this:

// Defining an array of numbers
var myArray = [1, 2, 3];

// Storing an array of numbers into the localStorage by converting it to a string
localStorage.setItem('myArray', JSON.stringify(myArray));

// Retrieving the array from localStorage and converting back to array from string
var retrievedArray = JSON.parse(localStorage.getItem('myArray'));

In this example, the myArray array is converted to a string using JSON.stringify() before it is stored in localStorage. When the value is retrieved from localStorage, it is converted back to an array using JSON.parse().

Wrap Up

I hope you understood how “passing” data between HTML pages works with localStorage.

The data isn’t really passed between the pages but stored in a common location to which all HTML pages have access.

Thanks for reading. Happy coding!

The post How to Pass a Variable from HTML Page to Another (w/ JavaScript) appeared first on codingem.com.

]]>
JavaScript How to Get Selected Text from a Textbox https://www.codingem.com/javascript-get-selected-text-from-textbox/ Thu, 16 Feb 2023 08:29:27 +0000 https://www.codingem.com/?p=13557 To get selected text from a textbox using JavaScript, you can use the following JavaScript code: You can try the above code solution by highlighting some text from the textbox below and clicking the button. Then whatever you highlight will appear in the alert box that pops up when you click the button. Highlight this […]

The post JavaScript How to Get Selected Text from a Textbox appeared first on codingem.com.

]]>
To get selected text from a textbox using JavaScript, you can use the following JavaScript code:

<script>
function show() {
  var text = document.getElementById("text");
  var selection = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
  alert(selection);
}
</script>

<TEXTAREA id="text">Highlight this text or parts of it and click the button below!</TEXTAREA><BR>
<INPUT type="button" onclick="show()" value="Select text and click here" />

You can try the above code solution by highlighting some text from the textbox below and clicking the button. Then whatever you highlight will appear in the alert box that pops up when you click the button.




Here’s what the outcome should look like:

A Step-by-Step Breakdown

In the above example, you saw a simple HTML/JavaScript code that demonstrates how to retrieve (and show) the selected text from a text area on a web page.

In case you had a hard time understanding the code, make sure to read the line-by-line breakdown.

First, let’s take a look at the HTML part of the snippet.

<TEXTAREA id="text">Highlight this text or parts of it and click the button below!</TEXTAREA>

This creates a simple text area element with the ID attribute set to “text“. This text area consists of the text that you can later highlight and grab using JavaScript.

<INPUT type="button" onclick="show()" value="Select text and click here" />

This HTML creates a button element with an onclick attribute that calls the JavaScript show function when the button is clicked. The show function doesn’t exist yet, it’s defined further down below.

Next, let’s take a look at the JavaScript code line by line.

var text = document.getElementById("text");

This line retrieves the text area element from HTML by its ID and stores it in a variable.

var selection = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);

This piece of code retrieves the currently selected text from the text area element and assigns it to a variable called “selection”.

The selectionStart and selectionEnd properties of the text area element determine the start and end positions of the selected text.

The substr method extracts the selected text from the text area’s value.

alert(selection);

Last but not least, an alert box shows the highlighted text when you’ve clicked the button.

Thanks for reading. Happy coding!

Read Also

How to Highlight Div Text with JavaScript

The post JavaScript How to Get Selected Text from a Textbox appeared first on codingem.com.

]]>
JavaScript Select All Text in Div with a Mouse Click https://www.codingem.com/javascript-click-to-select-all-div-text/ Wed, 15 Feb 2023 14:40:45 +0000 https://www.codingem.com/?p=13538 To select all div text with a single mouse click in JavaScript, you can use the following code: HTML: JavaScript: Here’s what the JavaScript function does step-by-step: Update: Because Internet Explorer is no longer in use, you might just want to remove the if-else function and use the code inside the else block. Test the […]

The post JavaScript Select All Text in Div with a Mouse Click appeared first on codingem.com.

]]>

To select all div text with a single mouse click in JavaScript, you can use the following code:

HTML:

<div id="sample" onclick="highlight('sample')"><b>Click this paragraph once and it's highlighted by JavaScript!</b></div>

JavaScript:

function highlight(id) {
    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(id));
        range.select();
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(id));
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
    }
}

Here’s what the JavaScript function does step-by-step:

  1. The function checks whether the document.selection property exists. This property is only available in older versions of Internet Explorer.
  2. If document.selection exists, the function creates a new text range and positions it to surround the text within the element with the ID id. It then selects the text range using the select() method.
  3. If document.selection does not exist, the function checks whether the window.getSelection() method exists. This method is available in modern browsers.
  4. If window.getSelection() exists, the function creates a new range that encompasses the element with the ID id. It then removes any existing selections using the removeAllRanges() method and adds the new range to the user’s selection using the addRange() method.

Update: Because Internet Explorer is no longer in use, you might just want to remove the if-else function and use the code inside the else block.

function highlight(id) {
    var range = document.createRange();
    range.selectNode(document.getElementById(id));
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
}

Test the above code solutions below by clicking the text element:

Click this paragraph once and it’s highlighted by JavaScript!

Alternative Solution: Use CSS

To make an HTML div text selectable with a single click of a button, you can use CSS. This way you don’t have to use JavaScript at all.

To pull this off, you can use the user-select specification as follows.

CSS:

.sample {
  -webkit-user-select: all;
  -ms-user-select: all;
  user-select: all;
}

HTML:

<div class="sample"><b>Click this paragraph once and it's highlighted by CSS!</b></div>

You can test this solution by clicking the paragraph below:

Click this paragraph once and it’s highlighted by CSS!

Careful with Content Editable Elements!

Content editable elements are HTML elements that can be edited by the user, such as div, span, and p elements. These elements have the contenteditable attribute set to “true”. When an element is content editable, the user can interact with its contents as if they were editing a document in a word processor.

When using JavaScript to select text in a content editable element, it’s important to use the selectNodeContents method instead of selectNode. The selectNodeContents method selects all of the contents of the element, whereas selectNode only selects the element itself.

Here’s an example:

HTML:

<div contenteditable="true" onclick="selectEditableText(this)">
    This is some editable text. Select me!
</div>

JavaScript:

function selectEditableText(element) {
    const range = document.createRange();
    range.selectNodeContents(element);
    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
}

In this code, we define a function called selectEditableText that takes one argument, element. This function creates a new range that encompasses all of the text within the element, selects that range, and adds it to the user’s selection.

In the HTML, we add an onclick attribute to the content editable div and pass this as an argument to the selectEditableText function. The this keyword refers to the element that triggered the event, which in this case is the content editable div.

Because the element is content editable, we use the selectNodeContents method to ensure that all of the text is selected.

You can try the solution by clicking the content editable div below:

This is some editable text. Select me!

Thanks for reading. Happy coding!

The post JavaScript Select All Text in Div with a Mouse Click appeared first on codingem.com.

]]>
JavaScript How to Calculate Age from Birthdate https://www.codingem.com/javascript-how-to-calculate-age-from-birthdate/ Fri, 10 Feb 2023 08:42:02 +0000 https://www.codingem.com/?p=13481 To calculate the age from birthdate in JavaScript, you can use this function: Here’s an example use of this function (called on 10th Feb 2023): Output: I hope this quick answer helps. If you have trouble understanding how this code works and what exceptions there are in calculating age (leap years), please read along. Problems […]

The post JavaScript How to Calculate Age from Birthdate appeared first on codingem.com.

]]>
To calculate the age from birthdate in JavaScript, you can use this function:

function age(birthdate) {
  const today = new Date();
  const age = today.getFullYear() - birthdate.getFullYear() - 
             (today.getMonth() < birthdate.getMonth() || 
             (today.getMonth() === birthdate.getMonth() && today.getDate() < birthdate.getDate()));
  return age;
}

Here’s an example use of this function (called on 10th Feb 2023):

const birthdate = new Date(2000, 2, 5); 
const ageValue = age(birthdate);
console.log(ageValue);

Output:

22

I hope this quick answer helps.

If you have trouble understanding how this code works and what exceptions there are in calculating age (leap years), please read along.

Problems with Leap Years

In order to calculate a person’s age, you need to take into account the fact that a year has a slightly different length than a calendar year.

A year is approximately 365.25 days long, while a calendar year is 365 days.

To make up for this difference, every fourth year (with the exception of years that are divisible by 100 but not divisible by 400) is considered a leap year.

This discrepancy causes issues when trying to calculate a person’s age based on the number of days from their birthdate.

For example, a person born on January 1st, 2000 would turn 18 years old 6575 days later on January 1st, 2018 with 5 leap years between the time range.

However, a person born on January 1st, 2001 would turn 18 only 6574 days later on January 1st, 2019, with only 4 leap years in between.

All I’m trying to say is that if someone is 6574 days old, you cannot tell if they are 17 or 18 without knowing more information about their birthdate because of the leap years.

To calculate a person’s age in JavaScript, use the Date object and follow these two steps:

  1. Subtract the birth year from the current year using the getFullYear method.
  2. Subtract 1 if the current month and day come before the birth month and day using the getMonth and getDate methods.

Let’s take another look at the code you already saw in the introduction with some comments and refactorings to make it more clear to you.

// Get today's date object
const today = new Date();

function age(birthdate) {
  // A bool that represents if today's day/month precedes the birth day/month
  const one_or_zero = (today.getMonth() < birthdate.getMonth()) ||
                      (today.getMonth() === birthdate.getMonth() &&
                       today.getDate() < birthdate.getDate());
  
  // Calculate the difference in years from the date object's components
  let year_difference = today.getFullYear() - birthdate.getFullYear();
  
  // The difference in years is not enough. 
  // To get it right, subtract 1 or 0 based on if today precedes the 
  // birthdate's month/day.
  // To do this, subtract the 'one_or_zero' boolean from 'year_difference'
  // (This converts true to 1 and false to 0 under the hood.)
  const age = year_difference - one_or_zero;
  
  return age;
}

// Example age check:
console.log(age(new Date(2000, 0, 1)));

Output:

23

Note that in JavaScript, the months in a Date object are 0-based (i.e. January is 0, February is 1, etc.), whereas in Python they are 1-based (i.e. January is 1, February is 2, etc.).

How about Leaplings?

A leapling is someone who was born on the leap day of a leap year (29th Feb).

This causes problems when calculating ages because, on a traditional year, that birthdate doesn’t exist. Usually, leaplings have their “official” birthday on 28th Feb or 1st Mar.

But technically, 1st Mar is the correct day because then a full year has passed since the leap day.

Let me show you how the above function’s logic handles the case where a person was born on February 29th, 2000 and we want to calculate their age on February 28th, 2001.

let birthdate = new Date(2000, 1, 29); // 29th Feb 2000
let today = new Date(2001, 1, 28);     // 28th Feb 2001

let year_difference = today.getFullYear() - birthdate.getFullYear();  // 2001 - 2000 = 1

let one_or_zero = (today.getMonth() < birthdate.getMonth()) ||
                  (today.getMonth() === birthdate.getMonth() && today.getDate() < birthdate.getDate()) ? 1 : 0;

let age = year_difference - one_or_zero;

console.log(age);  // Output: 0

Since February 28th, 2001 is before the person’s birthdate of February 29th, 2000, the value one_or_zero is 1. This means that their age would be calculated as year_difference - 1, which is 1 - 1 = 0.

So the logic correctly identifies that a year hasn’t passed between Feb 29th, 2000 and Feb 28th, 2001.

Wrap Up

In this tutorial, you learned how to calculate age in JavaScript using the built-in Date object.

Calculating age may seem straightforward, but it becomes more complex when considering the fact that a year is not exactly 365 days long. Instead, it is approximately 365.25 days.

I hope you found this tutorial helpful and enjoyable.

Happy coding!

The post JavaScript How to Calculate Age from Birthdate appeared first on codingem.com.

]]>
How to Get HTML Element (X, Y) Position with JavaScript https://www.codingem.com/javascript-get-html-element-position/ Thu, 08 Dec 2022 17:12:41 +0000 https://www.codingem.com/?p=13322 Getting the X, Y position of an HTML element in JavaScript can be accomplished using the following code: Where element is the HTML element whose position you want to retrieve. The offsetLeft and offsetTop properties give us its X and Y position. To get the position relative to the viewport (changes on the scroll and […]

The post How to Get HTML Element (X, Y) Position with JavaScript appeared first on codingem.com.

]]>
Getting the X, Y position of an HTML element in JavaScript can be accomplished using the following code:

let element = document.getElementById("example-element");
let x = element.offsetLeft;
let y = element.offsetTop;

console.log("Element X: " + x);
console.log("Element Y: " + y);

Where element is the HTML element whose position you want to retrieve.

The offsetLeft and offsetTop properties give us its X and Y position.

To get the position relative to the viewport (changes on the scroll and resizing), you can do:

let element = document.getElementById("example-element");
let x = element.getBoundingClientRect().left;
let y = element.getBoundingClientRect().top;

console.log("Element X (relative to viewport): " + x);
console.log("Element Y (relative to viewport): " + y);

I hope this quick answer helps. If you need examples, please read along. Also, I will show you how to get the position of the HTML element relative to the right corner and the bottom of the view.

Example

Let’s take a look at an example that demonstrates the above code in action in a real HTML page. Feel free to copy-paste the code and run it on your own setup.

<!DOCTYPE html>
<html>
  <head>
    <style>
      #example-element {
        position: absolute;
        left: 100px;
        top: 200px;
        width: 50px;
        height: 50px;
        background-color: blue;
      }
    </style>
  </head>
  <body>
    <div id="example-element"></div>
    <script>
      let element = document.getElementById("example-element");
      let x = element.offsetLeft;
      let y = element.offsetTop;
      console.log("Element X: " + x);
      console.log("Element Y: " + y);
    </script>
  </body>
</html>

Output:

Logging an HTML element position to the console with JavaScript

As you can see, the code logs the position of the blue HTML element into the console just like we defined it in the CSS.

Position Relative to Bottom and Right Corner

The above code showed you how to access the positions from the top and the left corner of the view.

In case you want to get the x, and y position relative to the bottom and right corner of the view, subtract the x, y position from the width and the height of the view.

Here’s an example:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #example-element {
        position: absolute;
        left: 100px;
        top: 200px;
        width: 50px;
        height: 50px;
        background-color: blue;
      }
    </style>
  </head>
  <body>
    <div id="example-element"></div>
    <script>
      let element = document.getElementById("example-element");
      let x = element.offsetLeft;
      let y = element.offsetTop;
      let bottom = window.innerHeight - (y + element.offsetHeight);
      let right = window.innerWidth - (x + element.offsetWidth);
      console.log("Element X: " + x);
      console.log("Element Y: " + y);
      console.log("Element Bottom: " + bottom);
      console.log("Element Right: " + right);
    </script>
  </body>
</html>

Notice that the bottom and right variables change based on the size of the viewport.

Here’s a view with a bit more space to the right. Now the Element Right is at 390 pixels:

By shrinking the window size, the Element Right position shrinks too.

Notice: The (X, Y) Position Doesn’t Change On Scroll

Notice that the x, and y position stays the same if you scroll the page.

For example, let’s make the page high enough so that one can scroll:

<!DOCTYPE html>
<html>
  <head>
    <style>
      body {
        height: 5000px;
      }
      #example-element {
        position: absolute;
        left: 100px;
        top: 200px;
        width: 50px;
        height: 50px;
        background-color: blue;
      }
    </style>
  </head>
  <body>
    <div id="example-element"></div>
    <script>
      window.onscroll = function() {
        let element = document.getElementById("example-element");
        let x = element.offsetLeft;
        let y = element.offsetTop;
        console.log("Element X: " + x);
        console.log("Element Y: " + y);
      };
    </script>
  </body>
</html>

Result:

As you can see from the image, the position remains the same.

Sometimes this behavior is not what you intended. You want to get the position with respect to the visible view.

For example, in the above image, the y position should be closer to 0 because the HTML element is almost at the top of the scrolled view.

How to Get (X, Y) Position Relative to Viewport?

To get the position of the element with respect to the view, you can use the getBoundingClientRect method instead of offsetLeft and offsetTop. getBoundingClientRect returns the size of an element and its position relative to the viewport.

Here is an updated HTML page with a high enough height to allow for scrolling. Beside, there’s a JavaScript call to the function to log the position of the element with respect to the view when scrolling:

<!DOCTYPE html>
<html>
  <head>
    <style>
      body {
        height: 5000px;
      }
      #example-element {
        position: absolute;
        left: 100px;
        top: 200px;
        width: 50px;
        height: 50px;
        background-color: blue;
      }
    </style>
  </head>
  <body>
    <div id="example-element"></div>
    <script>
      window.onscroll = function() {
        let element = document.getElementById("example-element");
        let rect = element.getBoundingClientRect();
        let x = rect.left;
        let y = rect.top;
        console.log("Element X: " + x);
        console.log("Element Y: " + y);
      };
    </script>
  </body>
</html>

Result:

Thanks for reading. Happy coding!

Read Also

JavaScript $ and _ Explained

The post How to Get HTML Element (X, Y) Position with JavaScript appeared first on codingem.com.

]]>
Double Quotes vs Single Quotes in JavaScript https://www.codingem.com/javascript-double-quotes-or-single-quotes/ Thu, 01 Dec 2022 09:25:29 +0000 https://www.codingem.com/?p=13332 You can use both single and double quotes in JavaScript. There’s no specific rule that dictates which one you should use. This means you can choose the style that suits you the best. But in the name of consistency, I recommend sticking with one style, though. Also, since ES6, you can also use template literals […]

The post Double Quotes vs Single Quotes in JavaScript appeared first on codingem.com.

]]>

You can use both single and double quotes in JavaScript.

There’s no specific rule that dictates which one you should use. This means you can choose the style that suits you the best.

let x = "John"
let y = 'John'

But in the name of consistency, I recommend sticking with one style, though.

Also, since ES6, you can also use template literals (backtick character) to create strings in JavaScript.

let z = `John`

Although the template literal is particularly useful when you need to embed values into strings.

let age = 20
let msg = `John is ${age} years old`

console.log(msg) // John is 20 years old

The Problem with Quotation Marks

The main issue with both single and double quotation marks in JavaScript arises when you need to use quotation marks inside a string.

Consider this example string:

console.log('Let's go')

Running this piece of code fails because of a syntax error:

This error happens because JavaScript sees the string in two parts instead of a single string.

  1. 'Let'
  2. s go'

Here JavaScript thinks that the single quote in the word Let’s terminates the string.

An easy way to avoid this error is by using double quotes instead of single quotes:

console.log("Let's go")

Output:

Let's go

Escaping Strings in JavaScript

Sometimes you might need to use single quotes even if it causes a problem like the above.

For example, let’s say you want to have a string like this:

console.log("Then he said: "let's go"")

Output:

console.log("Then he said: "let's go"")
            ^^^^^^^^^^^^^^^^

SyntaxError: missing ) after argument list

To fix this issue, you need to use what’s called escaping.

In short, escaping means using a backslash character to encode particular characters to avoid misinterpretation.

In this case, you want to escape the double quotation mark character to avoid JavaScript misinterpreting it as ending the string.

Here’s what it looks like:

console.log("Then he said: \"let's go\"")

Output:

Then he said: "let's go"

Template Literals

As of ES6, JavaScript has a third way to specify strings—template literals.

A template literal string is wrapped inside a pair of backticks instead of single or double quotes.

For example:

let age = 32
let msg = `Alice is ${age} years old`

In the previous section, you learned how to use escaping to place both single and double quotes inside a string.

But another option to do this is by using the template literals.

For example:

let msg = `He said: "Let's go!"`
console.log(msg // He said: "Let's go!"

Running the above code would fail had we used single or double quotes to create the message. But thanks to the template literals, the string was built successfully.

Which One Is Better: Single or Double Quotes?

Both single and double quotes are equally as great solutions to creating strings in JavaScript.

But there are some reasons why double quotes might be more desirable:

  1. Double quotation marks are already used in spoken language. For instance, in English, a double quotation mark identifies a passage of a quoted text.
  2. Double quotation marks require no escaping of apostrophes. For example “Let’s go to the beach” vs ‘Let\’s go to the beach’.
  3. Many other coding languages define strings with double quotes. For example, in PHP you can’t do backslash escaping with single-quote strings.
  4. In JavaScript, the JSON attribute labels and strings use double quotes. (Although the JSON string is wrapped around single quotes).

Thanks for reading. I hope you enjoy it! Happy coding!

The post Double Quotes vs Single Quotes in JavaScript appeared first on codingem.com.

]]>
4 Ways to Check If a String Contains a Substring in JavaScript https://www.codingem.com/javascript-check-if-string-has-substring/ Sun, 20 Nov 2022 11:08:03 +0000 https://www.codingem.com/?p=12898 The Short Answer There are several ways to check if a JavaScript string contains a substring. Here’s a short summary of the most notable ones. 1. string.indexOf() Use the indexOf() method. This method returns the index of the first occurrence of the substring in the string, or -1 if the substring is not found. For […]

The post 4 Ways to Check If a String Contains a Substring in JavaScript appeared first on codingem.com.

]]>
4 JavaScript methods to find substrings

The Short Answer

There are several ways to check if a JavaScript string contains a substring. Here’s a short summary of the most notable ones.

1. string.indexOf()

Use the indexOf() method. This method returns the index of the first occurrence of the substring in the string, or -1 if the substring is not found.

For example, let’s check if “word” exists in “Hello world!”:

var str = "Hello world!";
if (str.indexOf("world") >= 0) {
  console.log("There's a substring")
}

Output:

There's a substring

2. string.includes()

Use the includes() method. This method returns a boolean value indicating whether the string contains the substring or not.

For example, let’s check if “word” exists in “Hello world!”:

var str = "Hello world!";
if (str.includes("world")) {
  console.log("There's a substring")
}

Output:

There's a substring

3. string.search()

Using the search() method: This method is similar to indexOf(), but it supports regular expressions, allowing for more advanced substring matching.

For example, let’s check if “word” exists in “Hello world!”:

var str = "Hello world!";
if (str.search(/world/) >= 0) {
  console.log("There's a substring")
}

Output:

There's a substring

4. string.match()

Using the match() method: This method searches the string for a match against a regular expression, and returns an array containing the matched substrings, or null if no match is found.

For example, let’s check if “word” exists in “Hello world!”:

var str = "Hello world!";
if (str.match(/world/)) {
  console.log("There's a substring")
}

Output:

There's a substring

This is a comprehensive guide to checking if a string has a substring in JavaScript.

In case you found what you were looking for in the above answers, feel free to stop reading right here. But this is a wonderful chance to learn JavaScript at the same. To learn more about the above useful string methods and how they work, make sure to read along.

Let’s jump into it!

1. The string.indexOf() Method

JavaScript string.indexOf() method

The indexOf() method in JavaScript is used to search for a specified string in a given string and return the index at which the specified string is found. If the specified string is not found, the indexOf() method will return -1.

For example:

var str = "Hello, world!";

var n = str.indexOf("world");
var m = str.indexOf("test");

console.log(n);  // Output: 7
console.log(m);  // Output: -1

The indexOf() method can also take an optional second argument, which specifies the index at which the search should begin.

For example:

var str = "Hello, world!";

var n = str.indexOf("world", 5);

console.log(n);  // Output: 7

In the example above, the search for the string “world” begins at index 5 of the string “Hello, world!”. Since “world” appears at index 7 (you can count it with fingers to see that’s indeed the case), that is what the indexOf() method returns.

2. The string.includes() Method

JavaScript string.includes() method

The includes() method in JavaScript checks if a string contains a specified substring. It returns true if the specified substring is found in the given string, and false if it is not.

For example:

var str = "Hello, world!";

var isIncluded = str.includes("world");

console.log(isIncluded);  // Output: true

In the example above, the includes() method checks if the string “Hello, world!” contains the substring “world”. Since it does, the method returns true.

The includes() method can also take an optional second argument, which specifies the index at which the search should begin.

For example:

var str = "Hello, world!";

var isIncluded = str.includes("world", 5);

console.log(isIncluded);  // Output: true

Here the substring world is sought after the 5th index (6th character) of the string. Since “world” occurs at the 7th index it means there’s a substring “world” after starting the search from index 5.

Note that the indexOf() method can be used to achieve the same result as the includes() method. But the indexOf() returns the index at which the specified substring is found, whereas includes() returns a boolean value. So, it depends on the requirement of which method to use.

3. The string.search() Method

JavaScript string.match() method

The third option to search for substrings in JavaScript is by using the search() method. This method tries to find a specified substring in a string. It returns the index at which the specified string is found. If the specified string is not found, the search() method will return -1.

For example:

var str = "Hello, world!";

var n = str.search("world");

console.log(n);  // Output: 7

The search() method can also accept a regular expression as a parameter. In this case, the method will return the index at which the specified regular expression pattern is found in the given string.

Make sure to familiarize yourself with regular expressions (RegEx). Otherwise, the following example won’t make any sense to you.

For example:

var str = "Hello, world!";

var n = str.search(/[aeiou]/);

console.log(n);  // Output: 1

In the example above, the search() method searchs the first lowercase vowel (“a”, “e”, “i”, “o”, “u”) in the string “Hello, world!”. It returns the index at which the first match is found, which in this case is 1 (the “e” in “Hello”).

As you can see, the search() method not only achieves the same result as the indexOf() method, but also understands regular expressions. As such, the search() method is more powerful and flexible than the indexOf() method.

4. The string.match() Method

JavaScript string.search() method

Last but not least, let’s have a look at a similar method with search() called match(). The match() method searches for a substring in a string and return an array of matching substrings. If no matches are found, the match() method will return null. This method also accepts regex inputs.

Here is an example of how you can use the match() method:

var str = "Hello, world!";

var matches = str.match("world");

console.log(matches);  // Output: ["world"]

Here the match() method searches for the string “world” in the string “Hello, world!”. The method returns an array containing the matching string, which in this case is ["world"].

The match() method can also accept a regular expression as a parameter. In this case, it returns an array the substrings in the given string that match the specified regular expression pattern.

For example, let’s search for all the lowercase vowels in a string:

var str = "Hello, world!";

var matches = str.match(/[aeiou]/g);

console.log(matches);  // Output: ["e", "o", "o", "a"]

Here, the match() method searches for a pattern that matches any lowercase vowel in the string “Hello, world!”. The method returns an array of all the matching substrings. In this case, the result is ["e", "o", "o", "a"].

The match() method can be used to achieve the same result as the search() method, but it returns an array of matching substrings instead of the index at which the first match is found. Sometimes this makes the match() method more useful for extracting information from a string.

string.search() vs string.match()

The key difference between the match() and search() methods in JavaScript is the way in which they return the results of the search.

The search() method returns the index at which the first match is found, whereas the match() method returns an array of all the matching substrings.

Although you already saw a couple of examples, here’s one more that clearly demonstrates the difference between the two:

var str = "Hello, world!";

var n = str.search("world");
console.log(n);  // Output: 7

var matches = str.match("world");
console.log(matches);  // Output: ["world"]

Thanks for reading. Happy coding!

Read Also

An Ultimate Guide to RegEx

The post 4 Ways to Check If a String Contains a Substring in JavaScript appeared first on codingem.com.

]]>
3 Ways to Remove a Property from a JavaScript Object https://www.codingem.com/javascript-remove-object-properties/ Thu, 17 Nov 2022 12:52:33 +0000 https://www.codingem.com/?p=12914 The easiest way to remove a property from an object in JavaScript is by using the delete operator. For example, if you have an object called person with a property age, you can remove the age like this: After you run this code, the person object will no longer have an age property. Note that […]

The post 3 Ways to Remove a Property from a JavaScript Object appeared first on codingem.com.

]]>
Three main ways to remove properties from JavaScript objects

The easiest way to remove a property from an object in JavaScript is by using the delete operator.

delete objectName.propertyName;

For example, if you have an object called person with a property age, you can remove the age like this:

delete person.age;

After you run this code, the person object will no longer have an age property. Note that this will only remove the property from the object; it will not affect other objects that reference the same property.

You can also use the square-brackets accessing operator to remove an object property:

delete obj[prop];

This guide shows you the most common ways to remove properties from objects. If the above answer is enough, feel free to stop reading. But to explore JavaScript and learn useful methods and features, I recommend you keep reading the post. At the end of this guide, you will learn how to prevent a property from being deleted too!

Let’s jump into it!

1. The ‘delete’ Operator

delete operator in JavaScript removes properties

In JavaScript, the delete operator deletes a property from an object. More specifically, it removes the property and its value and returns true if the property was successfully deleted.

For example:

// Define an object with some properties
var myObject = {
  property1: "Hello",
  property2: "World"
};

// Delete the property2 property from the object
delete myObject.property2;

// Print the object to see the result
console.log(myObject);

Output:

{ property1: 'Hello' }

Here the delete operator deletes property2 from the myObject. After the delete operator is completed, the object will no longer have the property2 property and its value will be undefined.

Notice that another way to remove a property with the delete operator is by using the square brackets to access the property.

For example, let’s repeat the above example but use myObject['property2'] instead of myObject.property2.

var myObject = {
  property1: "Hello",
  property2: "World"
};

// Delete the property2 property from the object
delete myObject['property2'];

console.log(myObject);

2. The … Operator

The spread operator (...) removes JavaScript object properties

Another popular JavaScript operator you may be familiar with is called the spread operator or the “three-dots” operator (...).

In a sense, you can use this operator to remove a property from an object. In reality, it just creates a new object that lacks the property you ‘deleted’.

So to remove a property from an object using the spread operator, create a new object that contains all of the properties of the original object except for the property you want to remove.

For instance, let’s remove the prop2 from an object with three properties:

const obj = {
  prop1: 'value1',
  prop2: 'value2',
  prop3: 'value3'
};

// Create a new object with all of the properties of `obj` except `prop2`
const newObj = { ...obj, prop2: undefined };

console.log(newObj); // Output: { prop1: 'value1', prop3: 'value3' }

In this code:

  1. You create an object obj that has three properties: prop1, prop2, and prop3.
  2. You then create a new object called newObj that contains all of the properties of obj except prop2.

The latter step happens by using the spread syntax (...obj). When used this way, it simply re-creates a new object that includes all the original properties of obj. Then you set the prop2 to undefined in the new object which effectively removes it from the newly created object.

Notice that this method only creates a new object with the properties you want. It does not modify the original object. To truly remove a property from an object such that you modify the original object, use the delete operator:

const obj = {
  prop1: 'value1',
  prop2: 'value2',
  prop3: 'value3'
};

// Remove the `prop2` property from `obj`
delete obj.prop2;

console.log(obj); // Output: { prop1: 'value1', prop3: 'value3' }

3. Reflect.deleteProperty() Method

Reflect.deleteProperty method can also remove properties from JavaScript objects

The Reflect object in JavaScript is a built-in object that provides methods for interceptable JavaScript operations. It is similar to Proxy, but it does not allow you to define custom behavior for individual operations.

To delete a property from an object using the Reflect.deleteProperty() method, you can use the following syntax:

Reflect.deleteProperty(object, propertyName);

Here, object is the object from which you want to delete the property, and propertyName is a string that specifies the name of the property to delete. This method returns true if the property was successfully deleted, or false if the property could not be deleted (for example, if it is non-configurable).

Here is an example of how you can use this method to delete a property from an object:

// Define an object with a property that we want to delete
const obj = {
  name: "John Doe",
  age: 15
};

// Delete the "name" property from the object
const result = Reflect.deleteProperty(obj, "name");

// Print the result of the operation
console.log(result); // true
console.log(obj);    // { age: 15 }

In this example, the Reflect.deleteProperty() method deletes the name property from the obj object, and the result variable is set to true to indicate that the property was successfully deleted.

How to Prevent a Property from Being Deleted?

You might find it useful to know that JavaScript also lets you configure your objects such that you cannot remove a specific property.

To do this, use the Object.defineProperty() method, which allows you to define or modify the properties of an object. You can use this method to set the configurable property of a property to false, which prevents the property from being deleted.

For example, let’s prevent the name property from being deleted from the following object:

let myObject = { name: 'John', age: 30 };

Object.defineProperty(myObject, 'name', { configurable: false });

delete myObject.name;

console.log(myObject); // Output: { name: 'John', age: 30 }

As you can see, deleting the property name is not possible anymore. This is because of the restriction we placed on the object.

To make the name property removable, just set the configurable back to true.

let myObject = { name: 'John', age: 30 };

Object.defineProperty(myObject, 'name', { configurable: true });

delete myObject.name;

console.log(myObject); // Output: { age: 30 }

Thanks for reading. Happy coding!

Read Also

The Spread Operator (…) in JavaScript

The post 3 Ways to Remove a Property from a JavaScript Object appeared first on codingem.com.

]]>
JavaScript How to Find Duplicates in Array (without Removing) https://www.codingem.com/javascript-find-duplicates/ Thu, 10 Nov 2022 10:09:04 +0000 https://www.codingem.com/?p=13061 To find (and not delete) duplicates in a JavaScript array, you can use this function: Example use: Output: To learn how the above approach works, and what alternatives exist, please keep on reading. This guide shows you ways to find array duplicates and show them instead of deleting them. Besides, you will learn what performance […]

The post JavaScript How to Find Duplicates in Array (without Removing) appeared first on codingem.com.

]]>
To find (and not delete) duplicates in a JavaScript array, you can use this function:

function showDupes(arr) {
  return [...new Set(arr.filter((elem, idx, arr) => arr.indexOf(elem) !== idx))]
}

Example use:

const dupes = showDupes([1,1,1,2,2,2,3,4,5,6])
console.log(dupes)

Output:

[ 1, 2 ]

To learn how the above approach works, and what alternatives exist, please keep on reading. This guide shows you ways to find array duplicates and show them instead of deleting them. Besides, you will learn what performance issues there are with the naive approach and how to write a much quicker approach.

Let’s jump into it.

How to Find Duplicates in JavaScript Arrays

Given an array [1, 2, 4, 2, 5, 5, 5] you can instantly see that the values 2 and 5 are duplicates. But to let the JavaScript program know this, it must go through the values one by one and compare those with the rest of the values.

To see the values that are duplicated in a JavaScript array:

  • Pick the first array element and compare it with the rest of the elements one by one.
  • Pick the second element and compare it with the rest of the elements again.
  • This process repeats as long as there are values in the array.

To do this, you need a loop that goes through the elements one by one. Then inside that for loop, you need another loop that goes through the rest of the values one by one and compares them with the current number.

The For-Loop Approach

Here’s a nested for loop that implements the logic described above.

const array = [1, 2, 4, 2, 5, 5, 5];
const duplicates = [];

for (let i = 0; i < array.length; i++) {
  for (let j = i + 1; j < array.length; j++) {
    if (array[i] === array[j]) {
      duplicates.push(array[i]);
    }
  }
}

console.log(duplicates)

Output:

[ 2, 5, 5, 5 ]

This for-loop iterates through each element in the array and compares it to every other element in the array. If it finds a match, it adds the element there and jumps to check the next element. This process continues until there are no elements left in the array.

Now as you can instantly see, this approach works but it shows the duplicate values multiple times. To understand why this happens, just look at the image you saw earlier. For example, the 1st number 5 compares itself with the 2nd and 3rd number 5s and the 2nd number 5 compares itself with the 3rd number 5. This is why there are three 5s in the result.

To only show the duplicated value once, you need to keep track of the duplicate values already seen and make sure not to add an existing duplicate to the duplicates array.

The Improved For-Loop Approach

Here’s the improved version of the above for loop:

const array = [1, 2, 2, 4, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5];
const duplicates = [];

for (let i = 0; i < array.length; i++) {
  for (let j = i + 1; j < array.length; j++) {
    if (array[i] === array[j] && !duplicates.includes(array[i])) {
      duplicates.push(array[i]);
    }
  }
}

console.log(duplicates)

Output:

[ 2, 4, 5 ]

It works the exact same way as the previous for loop but it also checks that the duplicates array doesn’t already have the duplicate about to be added there (!duplicates.includes(array[i])).

The for-loop approach is a straightforward way to check what values occur in the array more than once. But if you’re looking for an alternative approach with less code, you can also implement the nested for-loop structure with the built-in array filter() function.

The Filter Method Approach

Here’s how you can check duplicate values with array filter() method:

const array = [1, 2, 4, 2, 5, 5, 5];
const duplicates = array.filter((element, index, arr) => arr.indexOf(element) !== index)

console.log(duplicates)

Output:

[ 2, 5, 5 ]

Here the filter() method takes each element of the array to an inspection one by one. In a sense, it’s the outer for loop when compared to the previous solution. The filter() method runs the function passed as an argument for each element to see if the element exists somewhere else in the array.

Thus, the indexOf() method is the inner for-loop. It checks the first index at which the current element occurs in the array.

Improved Filter Approach

Similar to the initial for-loop approach, this approach also shows duplicate values multiple times.

To fix the problem, you can place the duplicates into a set and convert the set back to an array. This works because a JavaScript set will automatically remove duplicate values.

const array = [1, 2, 4, 2, 5, 5, 5];
const duplicates = array.filter((element, index, arr) => arr.indexOf(element) !== index)
const unique_duplicates = [... new Set(duplicates)]

console.log(unique_duplicates)

Output:

[ 2, 5 ]

Create a Function

Last but not least, to make things look professional, it makes sense to place the filtering functionality into a separate JavaScript function:

function showDupes(arr) {
  return [...new Set(arr.filter((elem, idx, arr) => arr.indexOf(elem) !== idx))]
}

This is the piece of code you already saw in the introduction.

Performance

Both the for-loop and the filter approach are rather naive and perform poorly. This is because the array data is unsorted and a lot of unnecessary checks need to take place before you can know the duplicates.

For example, let’s measure how long it takes to check an array with 100,000 elements for duplicates:

const arr = [...Array(100_000).keys()].fill(0, 2, 4).fill(9, 10, 14)

console.time("time")
console.log(arr.filter((e, i, a) => a.indexOf(e) !== i))
console.timeEnd("time")

Output:

time: 4080.6533203125 ms

On my setup, it takes 4+ seconds.

This is a really poor performance and gets worse as the array size grows. In case you’re looking for an efficient way to check what are the duplicates in the array, you need a faster approach.

Solution: Sort First

One way to avoid doing excess comparisons is by sorting the data first and then using the filter on it.

Also, keep in mind the data is always not sortable. With the basic example of numbers, we can quite easily sort the data in an increasing/decreasing order.

When sorted, you can just compare a value to the previous neighbor. If the neighboring value is the same, it’s a duplicate. This way the filter() method only needs to run the function through once and check each consecutive numbers instead of comparing all numbers with the rest of the numbers.

Assuming the sorting algorithm was quick, this is a huge time-saver.

Here’s the better-performing approach that sorts the array first and then compares the neighbors only:

const arr = [...Array(100_000).keys()].fill(0, 2, 4).fill(9, 10, 14)

console.time("time")
console.log(arr.sort((a, b) => a > b ? 1 : -1).filter((e, i, a) => a[i-1] === e))
console.timeEnd("time")

Output:

time: 2.742919921875 ms

On my setup, this only took ~3ms which is 0.003 seconds, which is 1000+ times faster than the naive filter approach without sort.

Thanks for reading. Happy coding!

Read Also

7 Ways to Remove an Element from JavaScript Array

The post JavaScript How to Find Duplicates in Array (without Removing) appeared first on codingem.com.

]]>
5 Ways to Test If JavaScript Object is Empty https://www.codingem.com/check-if-javascript-object-is-empty/ Thu, 03 Nov 2022 11:10:23 +0000 https://www.codingem.com/?p=12950 The easiest way to check if a JavaScript object is empty is by using the Object.keys to check the length of properties to see if it’s 0. This guide teaches you 5 ways to check if a JavaScript object is empty. Although it only takes one, this is a great chance to learn more about […]

The post 5 Ways to Test If JavaScript Object is Empty appeared first on codingem.com.

]]>

The easiest way to check if a JavaScript object is empty is by using the Object.keys to check the length of properties to see if it’s 0.

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}

This guide teaches you 5 ways to check if a JavaScript object is empty.

Although it only takes one, this is a great chance to learn more about JavaScript. Besides, if you’re using jQuery or lodash libraries, you might find it useful to learn you can use those to check if an object is empty.

5 Ways to Check If an Object Is Empty

Here’s a quick overview of the methods you can use to check if an object is empty in JavaScript:

  1. Object.keys
  2. JSON.stringify
  3. Loop object properties
  4. jQuery isEmptyObject()
  5. Lodash isEmpty()

Where the 4th and 5th approaches only really make sense if you’re using those libraries in your code already.

Let’s take a closer look at these approaches.

1. Object.keys

In JavaScript, the Object.keys method returns an array of the object’s own enumerable properties. The properties considered when using Object.keys are those that can be accessed in a for-in loop, and those that have been assigned a non-symbolic, non-undefined value.

To use the Object.keys method, you pass in the object that you want to get the properties of as the argument. The method then returns an array of strings, where each string is the name of one of the object’s own enumerable properties.

To check if an object is empty in JavaScript using Object.keys, you can use the following code:

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}

To use this function, you can pass in any object that you want to check if it is empty.

For example:

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}

const obj = {};
const empty = isEmpty(obj); // true

console.log(empty)

2. JSON.stringify

In JavaScript, JSON.stringify() is a method that converts a JavaScript object or value to a JSON string. This method is often used when sending data to a server or when saving data to a file.

To check if a JavaScript object is empty, use the JSON.stringify() method to convert a JavaScript object to a JSON string and check if the result is an empty JSON object ‘{}’.

For example:

const obj = {}

// Convert the object to a JSON string
const json = JSON.stringify(obj);

// Check if the JSON string is empty
if (json === '{}') {
  console.log('The object is empty');
}

3. Loop Object Properties

To test if a JavaScript object is empty, you can use a for-in loop to loop through the object’s properties. If the object has no properties, then it is empty.

Here is an example:

function isEmpty(obj) {
  for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      return false;
    }
  }
  return true;
}

This function takes an object as its argument and returns true if the object is empty and false if it is not. It simply loops through the properties of the object and checks if they exist in the object. If none exists, the object is naturally empty.

4. jQuery (Library)

jQuery is a popular JavaScript library that makes it easier to add interactivity and other dynamic features to websites. It allows developers to easily manipulate the HTML elements on a page and create animations, handle user events, and perform other common JavaScript tasks. jQuery is widely used and is considered one of the most important tools for front-end web development.

jQuery has a variety of powerful built-in functions you can use to save time when writing code. For example, you can create fade animations or similar using jQuery.

One built-in function that jQuery comes with is the isEmptyObject() function. You can use this function to check if a JavaScript object is empty.

Notice that using this method does not make sense unless you’re using jQuery in your project already!

Here’s an example:

// create an object with some properties
var obj = {
    name: 'John Doe',
    age: 30
};

// check if the object has any properties
if ($.isEmptyObject(obj)) {
    console.log("Empty!")
} else {
    console.log("Not empty")
}

5. Lodash (Library)

Lodash is a JavaScript library that provides utility functions for common programming tasks.

It is a popular choice for front-end developers because it helps to reduce the amount of code to write, and makes it easier to work with arrays, objects, and other data types. With lodash, you can manipulate and iterate over arrays, objects, and strings, as well as functions for creating composite functions and working with asynchronous code.

To check if an object is empty using lodash, you can use the _.isEmpty() method. This method returns true if the object is empty, and false otherwise.

Assuming you have lodash included in your project, here’s an example:

const obj = {};

console.log(_.isEmpty(obj)); // logs "true"

Thanks for reading. Happy coding!

The post 5 Ways to Test If JavaScript Object is Empty appeared first on codingem.com.

]]>