Posts

Showing posts from 2022

JavaScript Type Conversion Table

The below table shows the conversion of various values to String, Number, and Boolean in JavaScript.  Value String Conversion Number Conversion Boolean Conversion 1 "1" 1 true 0 "0" 0 false "1" "1" 1 true "0" "0" 0 true "ten" "ten" NaN true true "true" 1 true false "false" 0 false

JavaScript - Implict null to number conversion

// null is 0 when used with number let num; num = 4 + null; console.log(num); // 4 num = 4 - null; console.log(num); // 4

JavaScript Implicit Boolean Conversion to Number

In Boolean true is 1, false is 0 let num; num = '4' - true; console.log(num); // 3 num = 4 + true; console.log(num); // 5 num = 4 + false; console.log(num); // 4

JavaScript implict conversion to number

You can implict convert a string to number using the following operators - , / , * let num; num = '6' - '4'; console.log(num); // 2 num = '4' - 2; console.log(num); // 2 num = '4' * 2; console.log(num); // 8 num = '4' / 2; console.log(num); // 2

JavaScript Implict Conversion to String

Implicit conversion is when JavaScript automatically converts one data type to another. let str; str = '1' + 2; console.log(str) // "12" str = '1' + true; console.log(str); // "1true" str = '1' + undefined; console.log(str); // "1undefined" str = '1' + null; console.log(str); // "1null"

Swapping array elements in JavaScript

Elements can be swapped using destructuring assignment expression var numbers = [1,2,3]; [numbers[2], numbers[1]] = [numbers[1], numbers[2]]; console.log(numbers); // [1,3,2] Without destructuring assignment, swapping two values requires a temporary variable

Ways to empty JavaScript array

There are different ways to empty an array in Javascript. By assigning an empty array var numbers =[1,3,5,6]; numbers =[]; By assigning array length to 0. var letters = ["a", "b", "c"]; letters.length = 0; By poping the elements of the array. var randomIntegers =[1,4,5,6]; while(randomIntegers.length > 0) { randomIntegers.pop(); } By using .splice() var cities =["Mumbai","Pune"]; cities.splice(0, cities.length)

Clone object in JavaScript

Object.assign() is a method which is used for cloning an object in JavaScript. Here is an example var person = { talk: "true" }; var male = Object.assign({}, person);