Posts

Showing posts with the label javascript

JavaScript variables - var, let and const

Instead of using the var keyword when defining variables, use the let and const keywords. This is due to the fact that whereas var is function-scoped, let and const are block-scoped. This indicates that var variables can be accessed from anywhere within the enclosing function, but let and const variables can only be accessed within the block in which they are declared. You may avoid unexpected behaviour and make your code simpler to read and comprehend by using let and const.  Here is an example: // Using `var` to declare a variable var x = 10 ; if (x > 5 ) { // `y` is accessible within the if block var y = 5 ; } // `y` is also accessible outside of the if block console . log (y); // 5 // Using `let` to declare a variable let x = 10 ; if (x > 5 ) { // `y` is only accessible within the if block let y = 5 ; } // `y` is not accessible outside of the if block console . log (y); // ReferenceError: y is not defined   As you can see, in the second example...

Remove duplicates from a JavaScript Array

In JavaScript, you may combine the indexOf() method and the filter() method to get rid of duplicates from an array function removeDuplicates(arr) { return arr.filter((el, index) => arr.indexOf(el) === index); } let numbers = [1, 2, 3, 3, 4, 4, 5]; let uniqueNumbers = removeDuplicates(numbers); console.log(uniqueNumbers); // [1, 2, 3, 4, 5] The removeDuplicates() function in this code accepts an array as an argument and produces a new array that is empty of duplicates. This is accomplished by creating a new array with the filter() method that only contains elements that are unique within the original array. A callback function is provided as an argument to the filter() method, which is used to filter each element of the array. By comparing the current element's index to the output of executing indexOf() on the original array, the callback function determines if the current element exists only once in the array. The element is added to the new array if the two indices a...

Basic JSON Interview question and answers

  1. What is JSON? Answer: JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format used for exchanging and storing data. 2. What are the benefits of using JSON? Answer: JSON is easy to read and understand, it is lightweight and can be parsed quickly, it is language-independent, and it is supported by many programming languages. 3. What are the main components of JSON? Answer: The main components of JSON are objects, arrays, strings, numbers,  booleans, and null. 4. How do you parse JSON data? Answer: JSON data can be parsed using the JSON.parse() method in JavaScript. 5. How do you convert JSON data to a string? Answer: JSON data can be converted to a string using the JSON.stringify() method in  JavaScript. 6. What is the difference between JSON and XML? Answer: JSON is simpler and more compact than XML. JSON does not require end tags and does not support attributes, while XML does. 7. How do you access JSON data? Answer: JSON data can be a...

Basic JavaScript Interview question and answers

Q 1 . What is JavaScript? A 1 . JavaScript is a scripting language used to create and control dynamic website content,  such as forms, animations, and interactive elements. Q 2 . What are the data types in JavaScript? A 2 . The data types in JavaScript include: strings, numbers, booleans,  objects, arrays, and functions. Q 3 . How do you define a variable in JavaScript? A 3 . Variables can be defined in JavaScript using the “var” keyword  followed by the variable name. Q 4 . What is the purpose of the “this” keyword in JavaScript? A 4 . The “this” keyword is used to refer to the object that the current  code is being executed in. Q 5 . What is the difference between == and === in JavaScript? A 5 . The “==” operator checks if two values are equal in value, while the “===”  operator checks if two values are equal in value and type. Q 6 . What is the purpose of the “undefined” keyword in JavaScript? A 6 . The “undefined” keyword is used to denote a variable that ha...

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);

JavaScript variables cheatsheet

Here are some different ways by which you can create variables in JavaScript var a; // variable var b = "init"; // string var c = "Hi" + " " + "Joe"; // = "Hi Joe" var d = 1 + 2 + "3"; // = "33" var e = [2,3,5,8]; // array var f = false; // boolean var g = /()/; // RegEx var h = function(){}; // function object const PI = 3.14; // constant var a = 1, b = 2, c = a + b; // one line let z = 'zzz'; // block scope local variable

Delete Object property in Javascript

Image
You can remove properties from an object using the delete operator. The delete operator removed both the value and the property from the object.   Here is an example

Remove falsy values from a JavaScript array using filter method

Here are examples of Falsy values (Falsy values returns false on evaluation) in JavaScript: undefined , null , NaN , 0 , "",  false We can use the JavaScript filter method to remove such values from our array var valueArray = ["Nishant", "IT", false, "India", 0, NaN, "JavaScript", undefined, null]; console . log ( valueArray . filter ( Boolean ) ); // returns ["Nishant", "IT", "India", "JavaScript"]

Truncate JavaScript array using length

Here are few examples to truncate JavaScript array using length property var chars = ["a", "w", "r", "t", "y", "y"]; console.log(chars); // ["a", "w", "r", "t", "y", "y"]; chars.length = 2; console.log(chars); // ["a", "w"]; chars.length = 0; console.log(chars); // [];

Convert JS array to an object

var languages = ["english", "hindi", "german", "spanish"]; var languagesObj = { ...languages }; console.log(languagesObj); // {0: "english", 1: "hindi", 2: "german", 3: "spanish"}

Delete v/s Splice for JavaScript Array

Use "splice" instead of "delete" to delete an item from an array because "Delete" replaces the item with undefined instead of the removing it from the array. var fruits = ["apple", "banana", "grapes"]; fruits.length; // return 3 delete fruits[1]; // return true fruits.length; // return 3 Instead var fruits = ["apple", "banana", "grapes"]; fruits.length; // return 3 fruits.splice(2,1) ; fruits.length; // return 2

Beautify JSON String

var myObj = {hello: "World"}; JSON.stringify(myObj, null, 4); // '{ // "hello": "world" // }'

String and Number Conversion in JavaScript

var myString = "999"; // Convert String to a number var myNumber = +myString; // → 999 // OR var myNumber = Number(myString) // → 999 // Convert String to negative number var myNegativeNumber = -myString; // → -999 // OR var myNegativeNumber = -Number(myString) // → -999