Categories
JavaScript JavaScript Basics

Using the Javascript Conditional Operator

The JavaScript conditional operator is a basic building block of JavaScript programs.

The conditional operator is also called the ternary operator.

It lets us write expression that returns one thing if a given condition it truthy and return something else otherwise.

The conditional operator is denoted by the ? operator.

We can use it as follows:

const foo = condition ? 'foo' : 'bar';

In the code above, if condition is truthy, then 'foo' is returned. Otherwise, 'bar' is returned.

Then the returned value is assigned to the foo variable.

The code is above is short for:

if (condition) {
  return 'foo';
}
else {
  return 'bar';
}

As we can see, the code above is much longer than using the conditional operator.

Since it’s save so much typing and space on the page, we should use the conditional operator instead of using if statements if we want to write code that returns one thing if a given condition is truthy and something else otherwise.

Categories
JavaScript JavaScript Basics

Introduction to JavaScript Strict Mode

JavaScript is a very forgiving language. It’s easy to write code that runs but has mistakes in it.

In this article, we’ll look at the benefits of using the strict mode directive.

Add Use Strict Mode Directive in Our Scripts

If we’re using old-school JavaScript script files, then we should add the 'use strict' directive into the top of our script.

Strict mode eliminates lots of silent errors by changing them to throw errors.

It also fixes mistakes that make optimizing our JavaScript code hard to increase their performance.

Also, it bans syntax that may be used in future JavaScript versions. Keywords like class can’t be used to declare variables, for example.

Strict mode can be applied to the whole script by putting the directive at the top or just in the function level by putting it in functions.

However, we should just apply it everywhere since it brings lots of benefits.

For instance, we can’t declare variables accidentally with 'use strict':

'use strict';
x = 1;

Since we have the 'use strict' directive on top of our script, we’ll get an error with the x = 1 expression since we haven’t declared x yet.

Without strict mode, this would create a global variable called x and assign 1 to it and pollute the global scope.

That isn’t good because it may overwrite another global variable with the same name.

Also, we can assign values to another global value like undefined or Infinity:

With strict mode on, code like the following will throw a TypeError:

var undefined = 1;
var Infinity = 1;

Assigning values to a non-writable property will also fail with a TypeError thrown:

var obj = {};
Object.defineProperty(obj, 'foo', { value: 42, writable: false });
obj.foo = 9;

We also wouldn’t be able to add properties that has preventExtensions called on it to prevent that:

var obj = {};
Object.preventExtensions(obj);
obj.foo = 'a';

The code above would throw a TypeError.

Attempting to delete undeletable properties will also throw an error. If we write something like:

'use strict';
delete Object.prototype;

Then we’ll get a TypeError.

Strict mode also requires function parameters to be unique. For instance, if we write:

'use strict';
function add(a, a, c) {  
  return a + a + c; 
}

Then we’ll get an ‘Uncaught SyntaxError: Duplicate parameter name not allowed in this context’ error since we have JavaScript strict mode on.

Also, it prevents numbers with a leading 0 from being used. The leading zero for octal numbers is rarely used and developers often assume that it’s still a decimal number.

Therefore if we have the following the strict mode throws an error:

'use strict';
var sum = 015 + 222;

If we run that, we get ‘Uncaught SyntaxError: Octal literals are not allowed in strict mode.’

The with statement is prohibited in strict mode. With strict mode, confusing code like this is prohibited:

'use strict';
var x = 17;
with(obj) {
  console.log(x);
}

The code above is confusing because x can either be obj.x or just x. It’s hard to tell what it’s referring to.

With strict mode on as we have above, we get ‘Uncaught SyntaxError: Strict mode code may not include a with statement’.

Doing anything to arguments or eval will also return syntax errors, so code like the following:

'use strict';
eval = 'foo';
arguments++;

Then we get ‘Uncaught SyntaxError: Unexpected eval or arguments in strict mode’ when we run the code above since we have JavaScript strict mode on.

We shouldn’t use these entities regardless of whether JavaScript strict mode is on, so it’s good that strict mode prevents expressions like these from running at least.

With strict mode on, the this value passed into call, apply, or bind aren’t boxed into an object.

Therefore, the original value is preserved if we pass in a primitive value. For instance, if we have:

'use strict';
function fn() {  
  return this;
}
console.log(fn.call(1) === 1);

Then we get 1 returned from fn instead of new Number(1), so we get that the console log output returns true.

Strict mode is enabled automatically for modules so we don’t need the directive on top of our code.

Conclusion

With so many benefits to strict mode, we should always enable it in old-school scripts.

If we use JavaScript modules, then it’s enabled by default, so we don’t have to worry about it.

We just have to put 'use strict' on top of all our scripts.

Categories
JavaScript JavaScript Basics

The Ultimate Guide to Manipulating Objects in JavaScript

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

Object.keys

Object.keys gets the top level list of keys of an object and returns an array of them. For example:

const a = {foo: 1, bar: 2};  
const length = Object.keys(a).length // 2

Object.getPropertyNames

Object.getPropertyNames also gets a list of all top level of keys of an object and return them as an array. For example:

const a = {foo: 1, bar: 2};  
const length = Object.getOwnPropertyNames(a).length // 2

for…in Loop

There is a special loop for looping through the keys of an object. You can do the following:

const a = {foo: 1, bar: 2};  
let keysCount = 0;  
for (let key in a) {  
    keysCount++;  
}  
console.log(keysCount) // 2

hasOwnProperty

You can check if an object has a property by calling hasOwnProperty of an object. For example:

const a = {foo: 1, bar: 2};  
a.hasOwnProperty(key); // true

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

Categories
JavaScript JavaScript Basics

Check If an Array Contains and Item in JavaScript

There’re a few ways to check if an array contains an item in JavaScript.

We can use the includes, some, filter, find, findIndex, or indexOf to do the check. All methods are part of the array instance.

includes

The includes method takes in a value and returns true if it’s in the array or false otherwise. The check is done with === operator.

For instance, we can call includes as follows:

const arr = [1, 2, 3];
const result = arr.includes(1);

In the code above, we called includes on arr and then check if 1 is in it.

Therefore, it should return true so result is true.

some

The some method takes a callback with the condition of the item to check for. We can use it as follows:

const arr = [1, 2, 3];
const result = arr.some(a => a === 1);

In the code above, we passed in a callback to the some method to check if any array entry, which is the value of a is 1.

It returns true if it’s in the array and false otherwise, so we should get the same result.

filter

The filter method returns and array with the items that meet the condition returned by the callback included.

For instance, we can call it as follows:

const arr = [1, 2, 3];
const result = arr.filter(a => a === 1).length > 0;

In the code above, we called the filter method with the same callback, which returns an array with 1 in it. Then we get the length property of it and the make sure it’s bigger than 0.

Therefore, we get the same result as before by calling filter and adding the length check.

find

The find method returns the first entry in the array that meets the given condition returned in the callback.

If the item isn’t found, then undefined is returned.

For instance, we can write the following:

const arr = [1, 2, 3];
const result = typeof arr.find(a => a === 1) !== 'undefined'

In the code above, we use the typeof operator to check if the array item returned by find is undefined or not. If it’s not undefined, then it’s found. Otherwise, it’s not.

Then we should get the same result as before.

findIndex

The findIndex method returns the index of the first element in the array that meets the given condition returned in the callback.

If the item isn’t found, then -1 is returned.

For instance, we can write the following code to use findIndex:

const arr = [1, 2, 3];
const result = arr.findIndex(a => a === 1) !== -1;

In the code above, we called findIndex with the same callback used in the previous examples to search if any item in the array is 1. Then we check if the returned index isn’t -1.

Therefore, it should return the same boolean result as before, which is true.

indexOf

indexOf returns the index of the item that matches the value passed in as the argument.

It returns -1 if the value isn’t found.

For instance, we can use it as follows:

const arr = [1, 2, 3];
const result = arr.indexOf(1) !== -1;

We checked the returned array against -1 so that we can check if it’s in the array.

So we should get the same results as before.

some, find and findIndex are suitable for searching for any object, while the rest are suitable for primitive values since they let search with any condition instead of just letting us pass in a value or variable.

Objects are compared with the === operator so it doesn’t compare the structure of an object.

Categories
JavaScript JavaScript Basics

Append Item to a JavaScript Array

Appending an item to an array in JavaScript is easy. There’re 2 ways to do it. Either we can use the spread operator, or we can use the array instance’s push method.

To use the spread operator, we can take the original array, spread it into a new array and put the new item at the end, and then we assign it back to the original array.

For instance, we can do that as follows:

let arr = [1, 2, 3];
arr = [...arr, 4];

In the code above, we declare the array with let so that we can do the assignment after it.

Then we append the new array entry to it by using the spread operator and then add the new entry as we did in the 2nd line and assign it back to the original array.

Now arr is [1, 2, 3, 4].

The other way is to call the push method which appends the array item in place.

To do that, we can write:

const arr = [1, 2, 3];
arr.push(4);

Now we have the same result, but we don’t have to assign the modified array back to the original array as we did with the first example, so we can use const to declare the array.

Appending an item to an array is easy with JavaScript.