Coding Examples from YouTube Videos Learn JavaScript PDF Guide Free sample code

Coding Examples from YouTube Videos Learn JavaScript

strict mode example

Use strict mode to enforce modern JavaScript syntax and catch errors early:

‘use strict’;

“use strict” is a directive in JavaScript that enables “strict mode”. Strict mode is a way to opt in to a “secure” version of JavaScript. When in strict mode, JavaScript will validate your code more strictly and throw errors when it encounters “unsafe” or undefined behaviors.

Here’s an example of using “use strict”:

‘use strict’;

x = 10; // ReferenceError: x is not defined

(function() {

  ‘use strict’;

  y = 20; // ReferenceError: y is not defined

})();

In the above example, both x and y are not declared with var, let, or const and are therefore considered global variables. When the code is run in strict mode, a ReferenceError is thrown, indicating that the variables are not defined.

It is recommended to use “use strict” at the beginning of every JavaScript file to ensure that the code is executed in strict mode and to take advantage of its security benefits.

Use const and let

Always declare variables with const or let, rather than var:

// Use let

let name = ‘John Doe’;

// Use const

const PI = 3.14;

var, let, and const are used to declare variables.

var is the oldest way to declare variables in JavaScript and has function scope. This means that a variable declared with var inside a function is only accessible within that function. If a var variable is declared outside of a function, it is considered a global variable and can be accessed from anywhere in the code.

var x = 10; // global scope

function example() {

  var y = 20; // function scope

}

console.log(x); // 10

console.log(y); // ReferenceError: y is not defined

let and const are introduced in ES6 and are block-scoped, meaning that a variable declared with let or const is only accessible within the block it was declared in.

let x = 10; // global scope

if (true) {

  let y = 20; // block scope

}

console.log(x); // 10

console.log(y); // ReferenceError: y is not defined

The difference between let and const is that let allows you to reassign the variable to a different value, while const does not. Once a variable is declared with const, its value cannot be changed.

const x = 10;

x = 20; // TypeError: Assignment to constant variable.

const y = [1, 2, 3];

y.push(4); // allowed, since arrays are mutable in JavaScript

It is recommended to use const by default, and only use let when you need to reassign the variable. This helps to ensure that your code is more readable, predictable, and secure.

Use Arrows functions

Use arrow functions instead of function for cleaner and concise code:

// Function expression

const multiply = (a, b) => a * b;

// Implicit return

const square = x => x * x;

Arrow functions, also known as “fat arrow” functions, are a shorthand way to declare anonymous functions in JavaScript. They were introduced in ECMAScript 6 (ES6) and are a more concise and less verbose alternative to regular function expressions.

Here’s an example of a regular function expression:

const sum = function(a, b) {

  return a + b;

};

console.log(sum(1, 2)); // 3

And here’s the equivalent arrow function:

const sum = (a, b) => {

  return a + b;

};

console.log(sum(1, 2)); // 3

Arrow functions have several advantages over regular function expressions:

Shorter syntax: Arrow functions are shorter and more concise, making your code easier to read and write.

Implicit return: If an arrow function only has one expression, the value of that expression is returned automatically. You can omit the return keyword and the curly braces.

const sum = (a, b) => a + b;

console.log(sum(1, 2)); // 3

Lexical this: Arrow functions have a lexical this binding, meaning that this refers to the surrounding scope and is not affected by the context in which the function is executed.

const person = {

  name: ‘John Doe’,

  greet: function() {

    setTimeout(function() {

      console.log(`Hello, my name is ${this.name}`);

    }, 1000);

  }

};

person.greet(); // Hello, my name is undefined

With arrow functions, this refers to the outer person object and the code works as expected:

const person = {

  name: ‘John Doe’,

  greet: function() {

    setTimeout(() => {

      console.log(`Hello, my name is ${this.name}`);

    }, 1000);

  }

};

person.greet(); // Hello, my name is John Doe

In conclusion, arrow functions are a powerful and convenient feature in JavaScript that allow you to write more concise, expressive, and predictable code.

Destructuring is a feature in JavaScript

Use Destructuring to get values from arrays

Make use of destructuring to extract values from arrays and objects into variables:

// Destructuring arrays

const colors = [‘red’, ‘green’, ‘blue’];

const [first, second, third] = colors;

// Destructuring objects

const person = {

  name: ‘John Doe’,

  age: 30,

  job: ‘Software Engineer’

};

const { name, age, job } = person;

Destructuring is a feature in JavaScript that allows you to extract values from arrays and objects and assign them to variables. It is a convenient and efficient way to extract multiple values from data structures and avoid unnecessary repetitions in your code.

Here’s an example of destructuring values from an array:

const numbers = [1, 2, 3, 4, 5];

const [first, second, …rest] = numbers;

console.log(first); // 1

console.log(second); // 2

console.log(rest); // [3, 4, 5]

In the above example, the const keyword is used to declare variables first, second, and rest. The values from the numbers array are then destructured and assigned to these variables using the square brackets []. The …rest syntax is called the “spread operator” and is used to extract all remaining elements of the array into a new array.

Here’s an example of destructuring values from an object:

const person = {

  name: ‘John Doe’,

  age: 30,

  location: ‘New York’

};

const { name, age, location } = person;

console.log(name); // John Doe

console.log(age); // 30

console.log(location); // New York

In the above example, the values from the person object are destructured and assigned to variables with the same name as the object properties. The curly braces {} are used to extract values from the object.

You can also give different names to the variables being destructured:

const person = {

  name: ‘John Doe’,

  age: 30,

  location: ‘New York’

};

const { name: fullName, age: personAge, location: city } = person;

console.log(fullName); // John Doe

console.log(personAge); // 30

console.log(city); // New York

Destructuring is a powerful feature in JavaScript that can make your code more readable, concise, and expressive. By extracting values from arrays and objects and assigning them to variables, you can avoid repetitive and verbose code and write more efficient and maintainable code.

Use template literals

Use template literals for string concatenation and embedding expressions:

const name = ‘John Doe’;

const message = `Hello, ${name}!`;

Template literals are string literals that allow you to embed expressions inside them. They are defined using backticks (“) instead of quotes (“”). The expressions inside template literals can be evaluated and the result is concatenated into the final string.

Here’s an example of using template literals:

const name = ‘John’;

const age = 30;

console.log(`My name is ${name} and I am ${age} years old.`);

// Output: My name is John and I am 30 years old.

In the above example, template literals are used to create a string that contains the values of the name and age variables. The expressions ${name} and ${age} are evaluated and their values are inserted into the string.

Another advantage of template literals is that they can span multiple lines:

const message = `Hello,

This is a message

spanning multiple lines.`;

console.log(message);

// Output:

// Hello,

//

// This is a message

// spanning multiple lines.

Template literals are also useful when working with complex expressions or computations inside strings. For example:

const a = 5;

const b = 10;

console.log(`The result of ${a} + ${b} is ${a + b}.`);

// Output: The result of 5 + 10 is 15.

In the above example, the template literal evaluates the expression a + b and inserts the result (15) into the string.

Template literals provide a more readable and convenient way to create strings in JavaScript. They can be used to concatenate variables, perform computations, and span multiple lines, making your code more readable and maintainable.

Use forEach over for loop

Prefer forEach over for loop for simple iterations:

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(number => console.log(number));

The forEach method is called on the numbers array. The first argument to forEach is a callback function, which is executed for each element in the array. The callback function takes a single argument, which represents the current element in the array being processed. In this case, the argument is named number, and its value is logged to the console.

Here’s another example that demonstrates how you can use forEach to modify the elements in an array:

const numbers = [1, 2, 3, 4, 5];

const double = [];

numbers.forEach(function(number) {

  double.push(number * 2);

});

console.log(double);

// Output: [2, 4, 6, 8, 10]

In this example, the forEach method is used to iterate over the numbers array and create a new array double that contains the double of each element in numbers. The push method is used to add each doubled number to the double array.

You can also use an arrow function as the callback function for forEach:

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(number => console.log(number));

// Output:

// 1

// 2

// 3

// 4

// 5

In this example, the arrow function number => console.log(number) is used as the callback function for forEach. The arrow function has a single parameter number and logs it to the console.

Note that the forEach method does not return a value and does not modify the original array. If you need to modify the original array, you should use a for loop or other iteration method.

In conclusion, the forEach method is a convenient and efficient way to iterate over an array and perform a specific action for each element. It is a powerful tool for processing arrays in JavaScript and can be used in a variety of situations to simplify your code.

use of higher-order functions 

Make use of higher-order functions like map, filter, and reduce to process arrays:

const numbers = [1, 2, 3, 4, 5];

// Use map

const double = numbers.map(number => number * 2);

// Use filter

const even = numbers.filter(number => number % 2 === 0);

// Use reduce

const sum = numbers.reduce((acc, number) => acc + number, 0);

A higher-order function is a function that takes one or more functions as arguments, or returns a function as its result. Higher-order functions are a fundamental concept in functional programming and are widely used in JavaScript for a variety of purposes.

Here’s an example of a higher-order function that takes a function as an argument:

function repeat(operation, num) {

  for (let i = 0; i < num; i++) {

    operation();

  }

}

function hello() {

  console.log(‘Hello’);

}

repeat(hello, 5);

// Output:

// Hello

// Hello

// Hello

// Hello

// Hello

In this example, the repeat function takes two arguments: operation and num. The operation argument is a function that is executed num times by the repeat function. In this case, the hello function is passed as the operation argument, and the repeat function is executed five times, which results in the hello function being called five times and the string “Hello” being logged to the console five times.

Here’s another example of a higher-order function that returns a function as its result:

function greaterThan(n) {

  return function(m) {

    return m > n;

  };

}

let greaterThan10 = greaterThan(10);

console.log(greaterThan10(9));  // false

console.log(greaterThan10(11));  // true

In this example, the greaterThan function takes a single argument n and returns a new function that takes a single argument m and returns true if m is greater than n, and false otherwise. The greaterThan10 variable is assigned the result of calling greaterThan(10), which returns a function that checks if its argument is greater than 10. The greaterThan10 function is then used to check if 9 and 11 are greater than 10, and the results are logged to the console.

Higher-order functions are widely used in JavaScript for tasks such as processing arrays, creating new functions with specific behavior, and composing functions. They allow you to write code that is more modular, flexible, and reusable, and they can greatly simplify complex tasks by breaking them down into smaller, more manageable components.

In conclusion, higher-order functions are a powerful concept in functional programming and are widely used in JavaScript to simplify complex tasks and make code more modular, flexible, and reusable. By taking functions as arguments or returning functions as results, higher-order functions provide a powerful tool for abstracting and composing functionality in your code.

Initialize variables with default values

Always initialize variables with default values to avoid undefined values:

// Default value

let name = ‘John Doe’;

// Default value with destructuring

const person = {

  name = ‘John Doe’,

  age: 30

};

const { name, age = 0 } = person;

In JavaScript, you can initialize variables with default values to ensure that they have a value, even if no value is explicitly assigned to them. There are several ways to initialize variables with default values in JavaScript, including using the || operator, the && operator, and the ?: operator.

Here’s an example of using the || operator to initialize a variable with a default value:

let x;

x = x || 10;

console.log(x);  // 10

In this example, the x variable is declared but not assigned a value. The line x = x || 10; uses the || operator to initialize x with a default value of 10 if x is falsy (i.e., if x is null, undefined, 0, NaN, “”, or false). In this case, since x is undefined, it is considered falsy and the default value of 10 is assigned to x.

Here’s an example of using the && operator to initialize a variable with a default value:

let y;

y = y && 20;

console.log(y);  // 20

In this example, the y variable is declared but not assigned a value. The line y = y && 20; uses the && operator to initialize y with a default value of 20 if y is truthy (i.e., if y is not falsy). In this case, since y is undefined, it is considered falsy and the default value of 20 is assigned to y.

Here’s an example of using the ternary operator ?: to initialize a variable with a default value:

let z;

z = z !== undefined ? z : 30;

console.log(z);  // 30

In this example, the z variable is declared but not assigned a value. The line z = z !== undefined ? z : 30; uses the ternary operator ?: to initialize z with a default value of 30 if z is undefined. In this case, since z is undefined, the default value of 30 is assigned to z.

In conclusion, initializing variables with default values in JavaScript is a common task that can be achieved using several different techniques, including the || operator, the && operator, and the ?: operator. By using these techniques, you can ensure that your variables always have a value, even if no value is explicitly assigned to them.