Categories
JavaScript JavaScript Basics

Cloning Arrays in JavaScript

There are a few ways to clone an array in JavaScript,

Object.assign

Object.assign allows us to make a shallow copy of any kind of object including arrays.

For example:

const a = [1,2,3];
const b = Object.assign([], a); // [1,2,3]

Array.slice

The Array.slice function returns a copy of the original array.

For example:

const a = [1,2,3];
const b = a.slice(0); // [1,2,3]

Array.from

The Array.slice function returns a copy of the original array. It takes array like objects like Set and it also takes an array as an argument.

const a = [1,2,3];
const b = Array.from(a); // [1,2,3]

Spread Operator

The fastest way to copy an array, which is available with ES6 or later, is the spread operator.

const a = [1,2,3];
const b = [...a]; // [1,2,3]

JSON.parse and JSON.stringify

This allows for deep copy of an array and only works if the objects in the array are plain objects. It can be used like this:

const a = [1,2,3];
const b = JSON.parse(JSON.stringify(a)); // [1,2,3]

Categories
JavaScript JavaScript Basics

How to Check if a Variable is a Number

We can check if a variable is a number in multiple ways.

isNaN

We can check by calling isNaN with the variable as the argument. It also detects if a string’s content is a number. For example:

isNaN(1) // false  
isNaN('1') // false  
isNaN('abc') // true

Note: isNaN(null) is true .

typeof Operator

We can use the typeof operator before a variable to check if it’s a number, like so:

typeof 1 == 'number' // true  
typeof '1' == 'number' // false
Categories
JavaScript JavaScript Basics

How to Round Numbers in JavaScript

JavaScript has multiple ways to round a number. Some choices are the Math.round , number.toFixed , andnumber.toPrecision . You can also write your own function to round a number up or down to the nearest increment.

Math.round

Math.round rounds a number to the nearest integer. If the decimal part of the number is less than 0.5, it is rounded down. Otherwise, if the decimal part of the number of 0.5 or higher then it will be rounded up. The function returns the rounded number as the value.

For example:

Math.round(12.5); // 13  
Math.round(12.49); // 12

Number.toFixed

You can set the number of digits that appears after the decimal place with toFixed function. The function returns the string representation of the number as the value. It can be used like this:

const a = 12.8888888888;  
const b = a.toFixed(2); // 12.88

Number.toPrecision

Number.toPrecision is similar to toFixed . It returns the string representation of a number, but you can round it to the specified number of significant digits which you can specify or let it automatically round to the correct number of significant digits.

const a = 12.8888888888;  
const b = a.toPrecision(2); // 13, since 2 significant digits is specified  
const c = a.toPrecision(); // 12.8888888888, since all digits are significant in the original number

Round to the nearest Increment

You can round to the nearest increment up or down you specify:

const roundNumberUp = (num, increment) => {   
  return Math.ceil(num / increment) \* increment;  
}  
console.log(roundNumberUp(12.2, 0.5)) // 12.5

What this does is take the original number, divide by the increment you want to round up to, then take the ceiling of that, then multiply by the increment. This means the number should always round up.

Similarly, you can round down to the nearest increment with floor.

const roundNumberUp = (num, increment) => {   
  return Math.floor(num / increment) \* increment;  
}  
console.log(roundNumberUp(12.2, 0.5)) // 12.5

What this does is take the original number, divide by the increment you want to round up to, then take the floor of that, then multiply by the increment. This means the number should always round down.

Categories
JavaScript JavaScript Basics

How To Do Common JavaScript Object Operations

Define New Object Literal

You can define object literals in JavaScript. An object does not have to an instance of a class in JavaScript.

You can define it like this:

const obj = { chicken: { hasWings: true }}

Define Object with Constructor

JavaScript lets you define objects that can be instantiated like a class with the new keyword.

You can define it like this:

const bird = function(hasWings){ this.hasWings = hasWings;}const chicken = new bird(true);  
console.log(chicken.hasWings); // true

Note the use of the function keyword instead of an arrow function. It is required to set this’s scope to the function itself.

Since ES6, you can define an object as an instance of a class.

For example:

class bird{  
  constructor(hasWings){  
    this.hasWings = hasWings;  
  }  
}const chicken = new bird(true);  
console.log(chicken.hasWings); // true

Get Keys of Object

Object.keys can be used to get all the top level keys of an object as strings. For example:

const chicken = { hasWings: true, bodyParts: [ {head: 1} ]};  
console.log(Object.keys(chicken)) // ['hasWings', 'bodyParts'];

Get Entries of an Object

Object.entriescan be used to get all the top level keys value entries of an object as arrays. For example:

const chicken = { hasWings: true, bodyParts: ['head', 'tail']};  
console.log(Object.entries(chicken)) // [['hasWings', true], ['bodyParts', ['head', 'tail']]];

Merge Two Objects

We can use the spread operation to combine two objects into one.

const a = {foo: 1};  
const b = {bar: 1};  
const c = {...a, ...b}; // {foo: 1, bar: 1}

If two objects have the same keys, the value of the one that is merged in last will override the earlier one.

const a = {foo: 1};  
const b = {bar: 1};  
const c = {bar: 2};  
const d = {...a, ...b, ...c};   
console.log(d) // {foo: 1, bar: 2}

Prevent Modification to an Existing Object

Object.freeze can be used to prevent an object from being modified. freeze takes an object as its argument and freezes an object in place.

For example:

let a = {foo: 1};  
a.foo = 2;  
Object.freeze(a);  
a.foo = 3;  
console.log(a) // {foo: 2}

Check If an Object Can Be Modified

Object.isFrozen can be used to check if an object is frozen by Object.freeze .

For example:

let a = {foo: 1};  
a.foo = 2;  
Object.freeze(a);  
a.foo = 3;  
console.log(Object.isFrozen(a)) // true

Clone Objects

If you assign an object to another variable, it just assigns the reference to the original object, so both variables will point to the original object. When one of the variables are manipulated, both will be updated. This is not always the desired behavior. To avoid this, you need to copy an object from one variable to another.

In JavaScript, this is easy to do. To shallow copy an object, we can use Objec.assign(), which is built into the latest versions of JavaScript. This function does a shallow copy, which means it only copies the top level of an object, while the deeper levels remain linked to the original object reference. This may not be desired if there is nested in your original object.

Here is an example of how to use Object.assign :

const a = { foo: {bar: 1 }}  
const b = Object.assign({}, a) // get a clone of a which you can change with out modifying a itself

You can also clone an array like this:

const a = [1,2,3]  
const b = Object.assign([], a) // get a clone of a which you can change with out modifying a itself

To do a deep copy of a object without a library, you can JSON.stringify then JSON.parse :

const a = { foo: {bar: 1, {baz: 2}}  
const b = JSON.parse(JSON.strinfy(a)) // get a clone of a which you can change with out modifying a itself

This does a deep copy of an object, which means all levels of an object are cloned instead of referencing the original object.

JSON.parse and JSON.stringify only works with plain objects, which means it cannot have functions and other code that runs.

With ES6, you can also use object destructuring to shallow clone objects, like so:

const a = { foo: {bar: 1}}  
const b = {...a} // get a clone of a which you can change with out modifying a itself

That’s it—a few simple steps for a few simple operations!

Categories
JavaScript JavaScript Basics

How to Copy Objects in JavaScript

Copying objects means making a new object reference to an object that has the same contents as the original. It is used a lot to prevent modifying the original data while you assign a variable to another variable. Because if you assign a variable to a new one, the new one has the same reference as the original object.

There are a few ways to clone objects with JavaScript. Some functions do shallow copying which means that not all levels of the object are copied, so they may still hold the reference the original object. A deep copy copies everything so that nothing references the original object, eliminating any confusion which arises from shallow copy.

Clone Object Using Built in JavaScript Functions

Is you assign a object to another variable, it just assigns the reference to the original object, so both variables will point to the original object. When one of the variables are manipulated, both will be updated. This is not always the desired behavior. To avoid this, you need to copy a object from one variable to another.

In JavaScript, this is easy to do. To shallow copy an object, we can use Objec.assign() , which is built into the latest versions of JavaScript. This function does a shallow copy, which means it only copies the top level of an object, while the deeper levels remain linked to the original object reference. This may not be desired if there is nested in your original object.

Here is an example of how to use Object.assign :

const a = { foo: {bar: 1 }}  
const b = Object.assign({}, a) // get a clone of a which you can change with out modifying a itself

You can also clone an array like this:

const a = \[1,2,3\]  
const b = Object.assign(\[\], a) // get a clone of a which you can change with out modifying a itself

To do a deep copy of a object without a library, you can JSON.stringify then JSON.parse :

const a = { foo: {bar: 1, {baz: 2}}  
const b = JSON.parse(JSON.strinfy(a)) // get a clone of a which you can change with out modifying a itself

This does a deep copy of an object, which means all levels of an object are cloned instead of referencing the original object.

JSON.parse and JSON.stringify only works with plain objects, which means it cannot have functions and other code that runs.

With ES6, you can also use object destructuring to shallow clone objects, like so:

const a = { foo: {bar: 1}}  
const b = {...a} // get a clone of a which you can change with out modifying a itself

Clone Object Using Third Party Libraries

There are many third parties which can do the same things. Lodash has _.clone and _.cloneDeep functions for shallow and deep copy. Underscore has a _.clone function for shallow copy.

Cloning objects is common operation that is easy to do with JavaScript. Now you can avoid bugs by not modifying objects that you are not intending to modify by copying them and then modify the copied object.