JavaScript – typeof Operator ”; Previous Next The typeof Operator The typeof operator in JavaScript is a unary operator used to get the data type of a particular variable. It is placed before its single operand, which can be of any type. Its returns a string value indicating the data type of its operand. JavaScript contains primitive and non-primitive data types. There are seven primitive or basic in JavaScript data types – number, string, boolean, undefined, null, symbol, and bigint. There is also a composite data type called object. The object data type contains three sub data type – Object, Array and Date. Syntax Following is the syntax of the typeof operator − typeof (operand); We can write the operand without parenthesis as follows − typeof operand; Parameter operand − It can be a value, variable or expression representing the object or primitive. In JavaScript, primitives are data that are not object and have no methods or properties. Return Value It returns the string value representing the data type of the operand. Datatypes Returned by typeof Operator Here is a list of the return values for the typeof Operator. Type String Returned by typeof Number “number” String “string” Boolean “boolean” Object “object” Function “function” Undefined “undefined” Null “object” Symbol “symbol” Bigint “bigint” There are seven primitive datatypes in JavaScript – number, string, boolean, bigint, undefined, null, and symbol. The typeof operator is useful to identify these primitive or basic datatypes. The typeof operator returns same datatype of the all primitive values except the null. It returns “object” for the null values. For object, date and array it returns “object” as datatype. For functions and classes, it returns “function” as datatype. Let”s use the typeof operator to identify these datatypes one by one. typeof 10; // returns ”number” typeof ”Hello World”; // returns ”string” typeof true; // returns ”boolean” typeof {name:”Tutorialspoint”}; // returns ”object” typeof function foo(){};// returns ”function” typeof undefined; // returns ”undefined” typeof null; // returns ”object” typeof Symbol(); // returns ”symbol” typeof 10n; // returns ”bigint” JavaScript typeof Operator to Check Number Type In JavaScript, number type represents numeric values. JavaScript uses a floating-point representation for all numbers. The JavaScript typeof operator returns ”number” for all types of numbers such as integers, floating points, zero, Infinity, NaN etc. typeof 10; //returns “number”; typeof -10; //returns “number”; typeof 0; //returns “number”; typeof 10.20; //returns “number”; typeof Math.LN10; //returns “number”; typeof Infinity; //returns “number”; typeof NaN; //returns “number”; typeof Number(”1”); //returns “number”; typeof Number(”hello”); //returns “number”; Example The example below demonstrates how to use the typeof operator to check number data types. <html> <body> <p> Using typeof operator to check number data type </p> <div id=”output”></div> <script> let num = 42; document.getElementById(“output”).innerHTML = typeof num; </script> <p>Set the variable to different value and then try…</p> </body> </html> Output Using typeof operator to check number data type number Set the variable to different value and then try… JavaScript typeof Operator to Check String Type Strings represent sequences of characters. The typeof operator helps identify string variables. The JavaScript typeof operator returns “string” for all type of strings, such as empty string, string of characters, string words, multiline string etc. typeof “10”; //returns “string”; typeof “”; //returns “string”; typeof “Hello World”; //returns “string”; typeof String(10); //returns “string”; typeof typeof 2; //returns “string”; Example In the example below we use typeof operator to check string datatype. <html> <body> <div id=”output”></div> <script> let str = “Hello World”; document.getElementById(“output”).innerHTML = typeof str; </script> <p>Set the variable to different value and then try…</p> </body> </html> Output string Set the variable to different value and then try… JavaScript typeof Operator to Check Boolean Type The boolean values represent true or false. The tyepof operand returns boolean for boolean variables. typeof true; //returns “boolean”; typeof false; //returns “boolean”; typeof Boolean(10); //returns “boolean”; Example In the example below, we use typeof operator to check boolean datatype. <html> <body> <div id=”output”></div> <script> let bool = true; document.getElementById(“output”).innerHTML = typeof bool; </script> <p>Set the variable to different value and then try…</p> </body> </html> Output boolean Set the variable to different value and then try… JavaScript typeof Operator to Check Symbol Type Symbols were introduced in ES6 and provide a way to create unique identifiers. Using typeof operator with symbols returns “symbol”. typeof Symbol(); //returns “symbol”; typeof Symbol(“unique values”); //returns “symbol”; Example In the example below, we use typeof operator to check Symbol datatype. <html> <body> <div id=”output”></div> <script> let sym = Symbol(“Hello”); document.getElementById(“output”).innerHTML = typeof sym; </script> <p>Set the variable to different value and then try…</p> </body> </html> Output symbol Set the variable to different value and then try… JavaScript typeof Operator to Check Undefined and Null The “undefined” type represents a lack of a value. The “null” type represents the absence of any object value. When using typeof operator with an undefined variable, it returns ”undefined”. Surprisingly, using typeof operator with null also returns “object”, which is a known quirk in JavaScript. typeof undefined; //returns “undefined”; typeof null; //returns “object”; Please note typeof operator will return “undefined” for both undeclared variable and declared but unassigned variables. Example In the example below, we use typeof operator to check undefined datatype. <html> <body> <div id=”output”></div> <script> let x; document.getElementById(“output”).innerHTML = typeof x; </script> <p>Set the variable to different value and then try…</p> </body> </html> Output undefined Set the variable to different value and then try… JavaScript typeof Operator to Check Object Type The JavaScript typeof operator returns “object” for all types of object such as JavaScript objects, arrays, dates, regex, etc. const obj = {age: 23}; typeof obj; //returns “object”; const arr = [1,2,3,4]; typeof arr; //returns “object”; typeof new Date(); //returns “object”; typeof new String(“Hello World”); //returns “object”; Example In the example below, we use typeof operator to check object datatype. <html> <body> <div id=”output”></div> <script> const person = {name: “John”, age: 34}; document.getElementById(“output”).innerHTML = typeof person; </script> <p>Set the variable to different value and then try…</p> </body> </html> Output object Set the variable to different value
Category: javascript
JavaScript – Reserved Keywords ”; Previous Next Reserved Keywords in JavaScript The reserved keywords in JavaScript are predefined keywords used to serve the built-in functionality of the programming language. For example, the var and let keywords are used to define variables, the function keyword is used to define the functions, etc. JavaScript contains more that fifty reserved keywords. In simple terms, you can”t use the reserved keywords as an identifier. If you do, you will get the conflicts, and the code will generate the wrong output or throw an error. For example, the below code will throw an error as ‘function’ is used as an identifier. var function = “Hello”; Reserved Keywords Here is the list of reserved keywords; you can’t use them as an identifier − abstract double implements return arguments else in switch await enum instanceof synchronized boolean eval int this break export interface throw byte extends let throws case false long transient catch final native true char finally new try class float null typeof const for package var continue function private void debugger goto protected volatile default if public yield delete implements short while do import static with double in super Reserved Keywords added in ES5 and ES6 Some new keywords are added in the ES5 and ES6 versions of JavaScript. However, some are currently in use, and some keywords are reserved for future versions. await class enum export extends import let Super Removed Reserved Keywords Some reserved keywords are removed from JavaScript, which you can’t use to achieve a particular functionality. Still, you can’t use the keywords below as an identifier as many browsers don’t support them. abstract boolean byte char double final float goto int long native short synchronized throws transient volatile JavaScript Objects, Properties, and Methods You should not use the name of JavaScript built-in objects, properties, and methods names as an identifier. JavaScript Built-in Objects Array ArrayBuffer Boolean DataView Date Error eval Float32Array Float64Array Function Generator GeneratorFunction Int8Array Int16Array Int32Array Intl JSON Map Math Number Object Promise Proxy RangeError ReferenceError Reflect RegExp Set String Symbol SyntaxError TypeError Uint8Array Uint8ClampedArray Uint16Array Uint32Array URIError WeakMap WeakSet JavaScript Built-in Properties length constructor prototype __proto__ caller callee JavaScript Methods toString shift indexOf split toLocaleString unshift lastIndexOf substr valueOf slice includes substring toLocaleDateString splice isArray toLowerCase toLocaleTimeString sort from toLocaleLowerCase toLocaleString forEach of toUpperCase toFixed map charAt toLocaleUpperCase toExponential filter charCodeAt trim toPrecision reduce codePointAt startsWith concat reduceRight normalize endsWith join every repeat match pop some replace test push find search reverse findIndex slice However, you can explore more built-in JavaScript methods and avoid using them as an identifier. Other Reserved Keywords JavaScript can be used with other programming languages like HTML, Java, etc. So, you should also avoid keywords that are reserved in HTML, Java, etc. Here is the list of other reserved keywords, and most of them are properties of the ‘window’ object. alert elements frameRate radio all embed hidden reset anchor embeds history screenX anchors encodeURI image screenY area encodeURIComponent images scroll assign escape offscreenBuffering secure blur event open select button fileUpload opener self checkbox focus option setInterval clearInterval form outerHeight setTimeout clearTimeout forms outerWidth status clientInformation frame packages submit close innerHeight pageXOffset taint closed innerWidth pageYOffset text confirm layer parent textarea constructor layers parseFloat top crypto link parseInt unescape decodeURI location password untaint decodeURIComponent mimeTypes pkcs11 window defaultStatus navigate plugin document navigator prompt element frames propertyIsEnum HTML Event Handlers You shouldn’t use the HTML even handlers as a variable name in JavaScript. Here, we have listed some of the event handlers. onclick ondblclick onmouseover onmouseout onmousemove onkeydown onkeyup onkeypress onfocus onblur onchange onsubmit onreset onload onunload onresize onscroll In short, you should avoid using all the above keywords as a variable or function name. Print Page Previous Next Advertisements ”;
JavaScript – Constants
JavaScript – Constants ”; Previous Next JavaScript Constants JavaScript constants are the variables whose values remain unchanged throughout the execution of the program. You can declare constants using the const keyword. The const keyword is introduced in the ES6 version of JavaScript with the let keyword. The const keyword is used to define the variables having constant reference. A variable defined with const can”t be redeclared, reassigned. The const declaration have block as well as function scope. Declaring JavaScript Constants You always need to assign a value at the time of declaration if the variable is declared using the const keyword. const x = 10; // Correct Way In any case, you can”t declare the variables with the const keyword without initialization. const y; // Incorrect way y = 20; Can”t be Reassigned You can”t update the value of the variables declared with the const keyword. const y = 20; y = 40; // This is not possible Block Scope A JavaScript variable declared with const keyword has block-scope. This means same variable is treated as different outside the blcok. In the below example, the x declared within block is different from x declared outside the blcok. So we can redeclare the same variable outsite the block { const x = “john”; } const x = “Doe” But we can”t redeclare the const varaible within the same block. { const x = “john”; const x = “Doe” // incorrect } Constant Arrays and Objects in JavaScript We can declare the arrays and objects using the const keyword, but there is a little twist in the array and object declaration. The variable with the const keyword keeps the constant reference but not the constant value. So, you can update the same array or object declared with the const keyword, but you can”t reassign the reference of the new array or object to the constant variable. Example (Constant Arrays) In the example below, we have defined the array named ”arr” using the const keyword. After that, we update the array element at the 0th index and insert the ”fence” string at the end of the array. In the output, you can observe that it prints the updated array. <html> <head> <title> Consant Arrays </title> </head> <body> <script> // Defining the constant array const arr = [“door”, “window”, “roof”, “wall”]; // Updating arr[0] arr[0] = “gate”; // Inserting an element to the array arr.push(“fence”); //arr = [“table”, “chair”] // reassiging array will cause error. // Printing the array document.write(arr); </script> </body> </html> When you execute the above code, it will produce the following result − gate,window,roof,wall,fence Example (Constant Objects) In the below example, we created the ”obj” object with the const keyword. Next, we update the ”animal” property of the object and insert the ”legs” property in the object. In the output, the code prints the updated object. <html> <head> <title> Constant Objects </title> </head> <body> <script> // Defining the constant object const obj = { animal: “Lion”, color: “Yellow”, }; // Changing animal name obj.animal = “Tiger”; // Inserting legs property obj.legs = 4; // Printing the object document.write(JSON.stringify(obj)); // obj = { name: “cow” } // This is not possible </script> </body> </html> It will produce the following result − {“animal”:”Tiger”,”color”:”Yellow”,”legs”:4} So, we can”t change the reference to the variables (arrays and objects) declared with the const keyword but update the elements and properties. No Const Hoisting Varaibles defined with const keyword are not hoisted at the top of the code. In the example below, the const variable x is accessed before it defined. It will cause an error. We can catch the error using try-catch statement. <html> <body> <script> document.write(x); const x = 10; </script> </body> </html> Here are some other properties of the variables declared with the const keyword. Block scope. It can”t be redeclared in the same scope. Variables declared with the const keyword can”t be hoisted at the top of the code. Constant variables value is a primitive value. Difference between var, let and const We have given the comparison table between the variables declared with the var, let, and const keywords. Comparison basis var let const Scope Function Block Block Hoisted Yes No No Reassign Yes Yes No Redeclare Yes No No Bind This Yes No No Which should you use among var, let, and const? For the block scope, you should use the let keyword. If you need to assign the constant reference to any value, use the const keyword. When you require to define the variable inside any particular block, like a loop, ”if statement”, etc. and need to access outside the block but inside the function, you may use the var keyword. However, you can use any keyword to define global variables. Redeclaring variables is not a good practice. So, you should avoid it, but if necessary, you may use the var keyword. Print Page Previous Next Advertisements ”;
JavaScript – let Statement
JavaScript – let Statement ”; Previous Next What is JavaScript let statement? The JavaScript let statement is used to declare a variable. With the let statement, we can declare a variable that is block-scoped. This mean a variable declared with let is only accessible within the block of code in which it is defined. The let keyword was introduced in the ES6 (2015) version of JavaScript. It is an alternative to the var keyword. The main reason behind introducing the let keyword is to improve the scoping behaviors of variables and the safety of the code. Variable Declaration with let statement Following is the syntax to declare a variable with let statement − let var_name = value Let”s have a look at some examples for variable declaration with let. let name = “John”; let age = 35; let x = true; Using let statement we can declare a variable of any datatypes, e.g., numeric, string, boolean, etc. JavaScript Block Scope vs. Function Scope The scope of the variable declared with the let keyword is a block-scope. It means if you define the variable with the let keyword in the specific block, you can access the variable inside that particular block only, and if you try to access the variable outside the block, it raises an error like ”variable is not defined”. { let x = “John”; } //here x can”t be accessed The var keyword has a function scope, meaning if you define the variable using the var keyword in any function block, you can access it throughout the function. function foo(){ if (true){ let x = 5 var y = 10 } // here x can”t be accessed while y is accessible } Sometimes, we require to define the variable with the same name in different blocks of one function. Conflicts may occur with the variable value if they use the var keyword. Example In the example below, we have defined the variable x using the let keyword and variable y using the var keyword. Also, we have assigned 10 and 20 values to both variables, respectively. We defined the test() function, redeclared the x and y variables inside it, and initialized them with 50 and 100 values, respectively. We print variable values inside the function, and it prints the 50 and 100 as it gives first preference to the local variables over global variables. <html> <head> <title> Variable declaration with let keyword </title> </head> <body> <script> let x = 10; var y = 20; function test() { let x = 50; var y = 100; document.write(“x = ” + x + “, y = ” + y + “<br/>”); } test(); </script> </body> </html> Example In the example below, we initialized the bool variable with a ”true” value. After that, we declared the variables x and y using the let and var keywords in the ”if” block. We print the value of the x and y variable inside the ”if” block. We can”t access the ”x” variable outside the ”if” block as it has blocked scope, but we can access variable y outside the ”if” block and inside the function block as it has function scope. <html> <head> <title> Variable declaration with let keyword </title> </head> <body> <script> function test() { let bool = true; if (bool) { let x = 30; var y = 40; document.write(“x = ” + x + “, y = ” + y + “<br/>”); } // x can”t be accessible here document.write(“y = ” + y + “<br/>”); } test(); </script> </body> </html> In this way, the let keyword is used to improve the scoping behaviors of the code. Redeclaring Variables in JavaScript You can”t redeclare the variables declared with the let keyword in the same block. However, you can declare the variables with the same name into the different blocks with the same function. Example In the example below, you can observe that variables declared with the let keyword can’t be redeclared in the same block, but variables declared with the var keyword can be redeclared in the same block. The code prints the value of the newly declared variable in the output. <html> <head> <title> Variable redeclaring </title> </head> <body> <script> function test() { if (1) { let m = 70; // let m = 80; // redeclaration with let keyword is not possible var n = 80; var n = 90; // redeclaration with var keyword is possible document.write(“m = ” + m + “, n = ” + n); } } test(); </script> </body> </html> Variable Hoisting The hoisting behaviors of JavaScript move the declaration of the variables at the top of the code. The let keyword doesn”t support hoisting, but the var keyword supports the hosting. Example In the example below, you can see that we can initialize and print the value of the variable n before its declaration as it is declared using the var keyword. <html> <head> <title> Variable hoisting </title> </head> <body> <script> function test() { // Hoisiting is not supported by let keyword // m = 100; // document.write(“m = ” + m + “<br/>”); // let m; n = 50; document.write(“n = ” + n + “<br/>”); var n; } test(); </script> </body> </html> You can uncomment the code using the let keyword and check the error in the web console, as it doesn”t support hoisting. Print Page Previous Next Advertisements ”;
JavaScript – Number
JavaScript – The Number Object ”; Previous Next The JavaScript Number object represents numerical data as floating-point numbers. It contains different properties (constants) and methods for working on numbers. In general, you do not need to worry about Number objects because the browser automatically converts number literals to instances of the number class. A JavaScript Number object can be defined using the Number constructor. Other types of data such as strings, etc., can be converted to numbers using Number() function. A JavaScript number is always stored as a floating-point value (decimal number). JavaScript does not make a distinction between integer values and floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard. Syntax The syntax for creating a number object is as follows − const val = new Number(number); In the place of number, if you provide any non-number argument, then the argument cannot be converted into a number, it returns NaN (Not-a-Number). We can also create the number primitives by assigning the numeric values to the variables − let num1 = 24; let num2 = 35.65; The JavaScript automatically converts the number primitive to the Number objects. So we can use all properties and methods of Number object on number primitives. Number Properties Here is a list of each property and their description. Sr.No. Property & Description 1 EPSILON It represents the difference between 1 and the smallest floating point number greater than 1. 2 MAX_SAFE_INTEGER It returns the maximum safe integer value. 3 MAX_VALUE The largest possible value a number in JavaScript can have 1.7976931348623157E+308. 4 MIN_SAFE_INTEGER It returns the minimum safe integer value. 5 MIN_VALUE The smallest possible value a number in JavaScript can have 5E-324. 6 NaN Equal to a value that is not a number. 7 NEGATIVE_INFINITY A value that is less than MIN_VALUE. 8 POSITIVE_INFINITY A value that is greater than MAX_VALUE 9 prototype A static property of the Number object. Use the prototype property to assign new properties and methods to the Number object in the current document. 10 constructor Returns the function that created this object”s instance. By default this is the Number object. Number Methods The Number object contains only the default methods (instance and static methods) that are a part of every object”s definition. Instance Methods Sr.No. Method & Description 1 toExponential() Forces a number to display in exponential notation, even if the number is in the range of standard notation. 2 toFixed() Formats a number with a specific number of digits to the right of the decimal. 3 toLocaleString() Returns a string value version of the current number in a format that may vary according to local settings. 4 toPrecision() Defines how many total digits (including digits to the left and right of the decimal) to display of a number. 5 toString() Returns the string representation of the number”s value. 6 valueOf() Returns the number”s value. Static Methods Sr.No. Method & Description 1 isNaN() It checks whether the value is a valid number or not. 2 isFinite() It checks whether the number is finite. 3 isInteger() Returns Boolean when the number is an integer value. 4 isSafeInteger() It ensures that the integer is a safe integer. 5 parseFloat() Parses the float value from the string. 6 parseInt() Parses the integer value from the string. Examples Let”s take a few examples to demonstrate the properties and methods of Number. Example: Creating Number Object In the example below, the num variable contains the number object having the value 20. In the output, you can see that type of the num variable is an object. <html> <body> <p id = “output”> </p> <script> const num = new Number(20); document.getElementById(“output”).innerHTML = “num = ” + num + “<br>” + “typeof num : ” + typeof num; </script> </body> </html> Output num = 20 typeof num : object Example: Number Properties In the example below, we have displayed some Number properties. You should try to print more properties. <html> <body> <div id=”output”></div> <script> document.getElementById(“output”).innerHTML = “Max Value : ” + Number.MAX_VALUE + “<br>” +”Min Value : ” + Number.MIN_VALUE + “<br>” +”Positive Infinity : ” + Number.POSITIVE_INFINITY + “<br>” +”Negative Infinity : ” + Number.NEGATIVE_INFINITY + “<br>” +”NaN : ” + Number.NaN + “<br>”; </script> </body> </html> Output Max Value : 1.7976931348623157e+308 Min Value : 5e-324 Positive Infinity : Infinity Negative Infinity : -Infinity NaN : NaN Example: Number Methods In the example below, we have used some properties of Number. You can try edit the program to use more methods. <html> <body> <div id=”output”></div> <script> const num = 877.5312 document.getElementById(“output”).innerHTML = “num.toExponetial() is : ” + num.toExponential()+ “<br>” +”num.toFixed() is : ” + num.toFixed() + “<br>” +”num.toPrecision(2) is : ” + num.toPrecision(2) + “<br>”; </script> </body> </html> Output num.toExponetial() is : 8.775312e+2 num.toFixed() is : 878 num.toPrecision(2) is : 8.8e+2 JavaScript Number() Function The Number() function converts the variable into a number. You can use it to change the data type of the variable. let num = Number(val) Here val is a variable or value to convert into a number. It doesn”t create a number object instead it returns a primitive value. Example We passed the integer and string value to the Number() function in the example below. In the output, the code prints the numeric values. The type of the num2 variable is a number, as the Number() function returns the primitive number value. <html> <body> <p id = “output”> </p> <script> let num = Number(10); document.getElementById(“output”).innerHTML = “num = ” + num + “<br>” + “typeof num = ” + typeof num; </script> </body> </html> Output num = 10 typeof num = number Example: Converting Numeric Strings to Numbers We can use the Number() function to convert numeric strings to numbers. Try the following example − <html> <body> <p id = “output”> </p> <script> let str = “102.34”; let num = Number(str); document.getElementById(“output”).innerHTML = “num = ” + num + “<br>” + “typeof num = ” + typeof num; </script> </body>
JavaScript – Comparison Operators ”; Previous Next JavaScript Comparison Operators The comparison operators in JavaScript compare two variables or values and return a boolean value, either true or false based on comparison result. For example, we can use the comparison operators to check whether two operands are equal or not. The comparison operators are used in logical expressions. A logical expression is evaluated to either true or false. The comparison operators are binary operators as they perform operations on two operands. The operands can be numerical, string, logical, or object values. There are eight comparison operators in JavaScript to perform different types of comparison. Here, we have given a table explaining each comparison operator with the example. Operator Description Example == Equal x == y != Not Equal x != y === Strict equality (equal value and equal type) x === y !== Strict inequality (not equal value or not equal type) x !== y > Greater than x > y < Less than x < y< >= Greater than or Equal to x >= y <= Less than or Equal to x <= y How comparison is done? If both operands are of same type, the comparison operators compare the values. However, if the operands are of different types, JavaScript perform appropriate type conversion for the comparison. This is known as type coercion. The comparison is done by checking the numerical values of the operands if both the operands are numbers. The strings are compared based on lexicographical ordering, using Unicode values. The following type coercion is done when a string is compared with a number. If the string contains only numeric value, it is converted to number type. If the string contains non-numeric values as well, it will be converted to NaN. If string is empty, it is converted to zero. The strict equality (===) and strict inequality (!==) operators perform strict comparison. These operators don”t perform type conversion before performing comparison operation. Dealing with falsy values There are some falsy values in JavaScript. JavaScript deals with these falsy values differently while performing the comparison. Followings are the flasy values − 0 (zero) false ” ” or ” ” (Empty String) null undefined NaN All comparison operators (excepts === and !==) converts false and empty string to zero before performing comparison. In addition to above, the less and, greater than operators (, >=) convert null to zero and undefined to NaN. JavaScript Equality (==) Operator The “equality” operator checks if the value of two operands are equal or not. It returns true if the operands are equal, otherwise it returns false. If the operands are of different types, it performs type conversion and then compare the operands. Let’s look at some examples of comparison with no type conversion. The both operands are of same type. const a = 10; const b = 20; a == 10; //true a == b; // false “Hello” == “Hello”; // true Now let’s check some example of comparison with type conversion. Here the operands are of different types. 5 == ”5”; // true 0 == false; // true 0 == ””; // true In the first example above, ”5” is converted to 5 (string to number conversion). The false and empty string (” ”), are converted to zero (0) before comparison. Example The following code shows how to use equality operator in JavaScript − <html> <body> <div id=”output”></div> <script> const a = 10; const b = 20; let result = (a == b); document.getElementById(“output”).innerHTML = “(a == b) => ” + result; </script> <p> Set the variables to different values and then try…</p> </body> </html> JavaScript Inequality (!=) Operator The “inequality” operator checks if the values of two operands are not equal. It returns true if the operands are not equal, otherwise it returns false. Same as the equality operator, type conversion is performed if the operands are not of same type. In the example below two values of same type are compared for inequality check. If the values are not equal, the inequality operator will return true. 10 != 10; // false 10 != 20; // true “Hello” != “Hello”; // false Let’s check for inequality when the operands are of different types . 10 != ”10”; // false 0 != false; // false Here in first example, ”10” is type casted to 10. Here string is converted to number type. In second example, false (Boolean value) is converted to zero (number). Example The following code shows how to use inequality operator in JavaScript. <html> <body> <div id=”output”></div> <script> const a = 10; const b = 20; let result = (a != b); document.getElementById(“output”).innerHTML = “(a != b) => ” + result; </script> <p> Set the variables to different values and then try…</p> </body> </html> JavaScript Strict Equality (===) Operator The “strict equality” operator checks whether the values and data types of the two operands are equal or not. It returns true if both operands are equal and of same type. In other words, it checks the equality of the operands without the type conversion. If the operands are of different types, it returns false without further checking the value. 10 === 10; // true 10 === 20; // false ”Hello”===”Hello”; // true 10 === ”10”; // false 0 === false; // false Example The following code shows how to use strict equality operator in JavaScript. <html> <body> <div id=”output”></div> <script> const a = 10; const b = 20; let result = (a === b); document.getElementById(“output”).innerHTML = “(a === b) => ” + result; </script> <p> Set the variables to different values and then try…</p> </body> </html> Strict Inequality (!==) Operator The “strict inequality” operator checks whether the two operands are not equal in value or type. It returns true if the operands are of same type but not equal or are of different types. Same as strict equality operator, it also first checks the inequality of operands without type conversion. If the operands are of different
JavaScript – Arrow Functions
JavaScript – Arrow Functions ”; Previous Next Arrow Functions The arrow functions in JavaScript allow us to create a shorter and anonymous function. Arrow functions are written without “function” keyword. The JavaScript arrow functions are introduced in ES6. Before ES6, we can define a JavaScript function with function declaration or function expression. The function expressions are used to define anonymous functions. The arrow functions allow us to write the function expressions with shorter syntax. Let”s look at the below syntax to write a function expression − const varName = function(parameters) { // function body }; The above function expression can be written as an arrow function − const varName = (parameters) => { // function body }; Here the “function” keyword is removed and after parenthesis we added “=>”. Syntax The syntax to use the arrow function in JavaScript is as follows. const varName = (p1, p2, … pN) => Expression; OR const varName = (p1, p2, …pN) => { // function body }; Here the parameters p1, p2, …, pN are optional. We can use the variable name followed by pair of parentheses to invoke the arrow function. Arrow Function with Single Statement When the arrow function contains a single statement, we don”t need to write the ”return” keyword and braces (curly brackets). const add = (x, y) => x +y; Please note, we can always write an arrow function with return keyword and braces. const add = (x, y) => {return x + y}; Example In the example below, the arrow function contains a single statement, so we don”t need to use the curly braces or return statement. <html> <body> <p id = “output”> </p> <script> const divide = (x, y) => x / y; document.getElementById(“output”).innerHTML = divide(10, 5); </script> </body> </html> Output 2 Arrow Function with Multiple Statements When the function body contains multiple statements, we should always use the ”return” statement to return a value. Also we should use the curly brackets. Example In the example below, the arrow function contains multiple statements, so we need to use the braces or return statement. <html> <body> <p id = “output”> </p> <script> const divide = (x, y) => { let res = x / y; return res; }; document.getElementById(“output”).innerHTML = divide(10, 5); </script> </body> </html> Output 2 Note when we use block body using braces, we must use return statement. Arrow Functions Without Parameters The parameters p1, p2, …, pN, in the above syntaxes are options. We can write an arrow function without any parameters. const greet = () => “Hello World!”; We can also write using block body using braces and return keyword − const greet = () => {return “Hello World!”;}; Example <html> <body> <p id = “output”> </p> <script> const greet = () => “Hello World!”; document.getElementById(“output”).innerHTML = greet(); </script> </body> </html> Output Hello World! Arrow Function with Parameters Example: Arrow function with a single parameter The below code demonstrates that when you need to pass a single parameter to the function, you don”t need to write parameters in the pair of parenthesis. <html> <body> <p id = “output”> </p> <script> const divide = x => 20 / x; let res = divide(2); document.getElementById(“output”).innerHTML = “The value returned from the arrow function is: ” + res; </script> </body> </html> Output The value returned from the arrow function is: 10 Example: Arrow function with multiple parameters We pass the multiple parameters to the arrow function expression in the code below. When the body of the arrow function contains multiple statements, we need to write it inside the curly braces and use the return statement to return the value. <html> <body> <p id = “output”> </p> <script> const sum = (a, b, c, d) => { let sum = a + b + c + d; return sum; }; let res = sum(10, 30, 45, 60); document.getElementById(“output”).innerHTML = “The sum of 10, 30, 45, and 60 is: ” + res; </script> </body> </html> Output The sum of 10, 30, 45, and 60 is: 145 Arrow Function as an Expression The arrow function can easily be used as an expression due to its shorter syntax. Example In the below code, we use the ternary operator, and based on the boolean value of the ”isMul” variable, we assign the arrow function expression to the ”func” variable. After that, we use the ”func” variable to call the arrow function stored in that. <html> <body> <p id=”output”> </p> <script> let isMul = true; const func = isMul ? () => { let res = 5 * 5; document.getElementById(“output”).innerHTML += “The multiplication value is: ” + res + “<br>”; } : () => { let res = 5 + 5; document.getElementById(“output”).innerHTML += “The sum value is: ” + res + “<br>”; }; func(); </script> </body> </html> Output The multiplication value is: 25 Arrow Function with Default Parameters Example The below code explains how programmers can pass the default parameters to the arrow function. It is similar as we pass default parameters to the standard function definition. <html> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); let isMul = true; const mul = (a = 10, b = 15) => a * b; output.innerHTML += “mul(5, 8) = ” + mul(5, 8) + “<br>”; output.innerHTML += “mul(6) = ” + mul(6) + “<br>”; output.innerHTML += “mul() = ” + mul() + “<br>”; </script> </body> </html> Output mul(5, 8) = 40 mul(6) = 90 mul() = 150 Benefits of Using Arrow Functions Here, we have explained the benefits of using the arrow functions. Shorter syntax − The arrow function decreases the code size to define the function. Implicit return − To return the resultant value of the expression from the arrow function containing only a single statement, developers don”t need to use the return keyword. Ease to use as expression − The arrow function can be easily used as an expression. Limitations of Using Arrow Function There are some limitations of arrow functions, which we have
JavaScript – Overview
Javascript – Overview ”; Previous Next What is JavaScript? JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side script to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities. JavaScript is a single-threaded programming language that we can use for client-side or server-side development. It is a dynamically typed programming language, which means that we don’t care about variable data types while writing the JavaScript code. Also, it contains the control statements, operators, and objects like Array, Math, Data, etc. JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded in Netscape and other web browsers. The ECMA-262 Specification defined a standard version of the core JavaScript language. JavaScript is a lightweight, interpreted programming language. Designed for creating network-centric applications. Complementary to and integrated with Java. Complementary to and integrated with HTML. Open and cross-platform History of JavaScript JavaScript is developed by Brendan Eich, a computer scientist and programmer at Netscape Communications Corporation. The initial name of the JavaScript was the ”Mocha”. After that, it changed to ”LiveScript”, and then ”JavaScript”. Between 1996 and 1997, the European Computer Manufacturers Association (ECMA) standardized JavaScript. After that, 3 revisions of the JavaScript have been done. In ES5 (2009), Node.js was introduced to use JavaScript as a server-side language. The ES6 (2015) was a significant revision of JavaScript, introducing advanced features into JavaScript. Currently, JavaScript has reached the version ES14. ES14 (ECMAScript 2023) the 14th version, was released in June 2023. Client-Side JavaScript Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser. It means that a web page need not be a static HTML but can include programs that interact with the user, control the browser, and dynamically create HTML content. The JavaScript client-side mechanism provides many advantages over traditional CGI server-side scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in a form field. The JavaScript code is executed when the user submits the form, and only if all the entries are valid they would be submitted to the Web Server. JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the user initiates explicitly or implicitly. The Popular client-side libraries for JavaScript development are ReactJS, NextJS, Vue JS, Angular JS, etc. Server-Side JavaScript In the early days, JavaScript was used for front-end development to add behaviors to HTML pages. Since 2009, JavaScript is also used as a server-side programming language to build scalable and dynamic web applications. Node.js is one of the best and most popular JavaScript runtime environments for building the server of applications using JavaScript. Using Node.js, we can execute the JavaScript code outside the browser and manage the server task. The server tasks can be an interaction with the database, APIS, file handling, or maybe network communication. Due to the event-driven architecture of Node.js, it is faster than other server-side programming languages. Advantages of JavaScript The merits of using JavaScript are − Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server. Immediate feedback to the visitors − They don”t have to wait for a page reload to see if they have forgotten to enter something. Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard. Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors. Limitations of JavaScript We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features − Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reasons. JavaScript cannot be used for networking applications because no such support is available. JavaScript doesn”t have any multi-threading capabilities. Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into otherwise static HTML pages. Imperative vs. Declarative JavaScript The imperative and declarative is a programming paradigm, and JavaScript follows both. Imperative JavaScript − In imperative JavaScript, we write code in the manner that the code describes the steps to get the output. So, we are concerned about the code execution flow and output both. For example, to sum all array elements, if we write code for loop, it explains each step to get the sum. Declarative JavaScript − In declarative JavaScript, we don”t need to worry about execution flow, but we should get the correct output at the end. For example, we use a built-in array.reduce() method to get a sum of array elements. Here, we don’t concern about how reduce() method is implemented in the library. JavaScript Development Tools One of the major strengths of JavaScript is that it does not require expensive development tools. You can start with a simple text editor such as Notepad. Since it is an interpreted language inside the context of a web browser, you don”t even need to buy a compiler. Here are various free tools which can be helpful while developing applications with JavaScript. Visual Studio Code (VS Code) − The VS Code is a code editor used by most developers to write JavaScript code. It is feature rich and contains various extensions that can increase the productivity of any developer. Chrome dev tools − Programmers may use the Chrome dev tools to debug the JavaScript code. However, they can use the debugging tool
JavaScript – Enabling
Enabling JavaScript in Browsers ”; Previous Next Enabling JavaScript All modern browsers come with built-in support for JavaScript, and it has enabled JavaScript by default. Frequently, you may need to enable or disable this support manually. This chapter explains how to turn JavaScript support on and off in your browsers: Chrome, Microsoft Edge, Firefox, Safari, and Opera. JavaScript in Chrome Here are the steps to turn on or turn off JavaScript in Chrome − Click the Chrome menu at the top right-hand corner of your browser. Select the Settings option. Click on the Privacy and Security tab from the left sidebar. Click Show advanced settings at the end of the page. Next, click on the Site Settings tab. Now, scroll to the bottom of the page, and find the content section. Click on the JavaScript tab in the content section. Here, you can select a radio button to turn JavaScript on or off. Also, you can add the URLS of the custom website to block and unblock JavaScript on particular websites. JavaScript in Microsoft Edge Here are simple steps to turn on or turn off JavaScript in your Microsoft Edge − Click Edge menu (three dots) at top right-hand corner of the edge browser. Follow More Tools → Internet Options from the menu. Select Security tab from the dialog box. Click the Custom Level button. Scroll down till you find Scripting option. Select Enable radio button under Active scripting. Finally click OK and come out. To disable JavaScript support in your Microsoft Edge, you need to select Disable radio button under Active scripting. JavaScript in Firefox Here are the steps to turn on or turn off JavaScript in Firefox − Open a new tab → type about: config in the address bar. Then you will find the warning dialog. Select I’ll be careful, I promise! Then you will find the list of configure options in the browser. In the search bar, type javascript.enabled. There you will find the option to enable or disable javascript by right-clicking on the value of that option → select toggle. If javascript.enabled is true, it converts to false upon clicking toggle. If javascript is disabled, it gets enabled upon clicking toggle. JavaScript in Safari When you install the Safari web browser, JavaScript comes installed by default. If you have disabled it and want to enable it, follow the steps below. Click on the safari menu from the top-left corner. Select the preferences in the dropdown menu. It will open a new window. Open the security tab. Check the Enable JavaScript checkbox in the ‘web content’ section to enable the javascript. You can disable the JavaScript by unchecking the checkbox. Now, close the preference window and reload the web page. JavaScript in Opera Here are the steps to turn on or turn off JavaScript in Opera − Follow Tools → Preferences from the menu. Select the Advanced option from the dialog box. Select Content from the listed items. Select Enable JavaScript checkbox. Finally, click OK and come out. To disable JavaScript support in your Opera, you should not select the enable JavaScript checkbox. JavaScript in Brave The Brave is well-known for its security and privacy. So, It doesn’t allow us to disable the JavaScript permanently, but we can disable the JavaScript for the particular website by following the below steps. Open the website URL to disable the browser for it. Now, Click on the ‘Brave Shields’ icon in the address bar. Find the Scripts option in the Shields panel. The default value of the Scripts is “Allow Scripts”. If you want to disable JavaScript, choose the “Block Scripts” option. Warning for Non-JavaScript Browsers If you have to do something important using JavaScript, then you can display a warning message to the user using <noscript> tags. You can add a noscript block immediately after the script block as follows − <html> <head> <script> document.write(“Hello World!”) </script> <noscript> Sorry…JavaScript is needed to go ahead. </noscript> </head> <body> </body> </html> Now, if the user”s browser does not support JavaScript or JavaScript is not enabled, then the message from </noscript> will be displayed on the screen. Print Page Previous Next Advertisements ”;
JavaScript – Placement
JavaScript – Placement in HTML File ”; Previous Next JavaScript Placement in HTML File There is flexibility to place JavaScript code anywhere in an HTML document. However, the most preferred ways to include JavaScript in an HTML file are as follows − Script in <head>…</head> section. Script in <body>…</body> section. Script in <body>…</body> and <head>…</head> sections. Script in an external file and then include in <head>…</head> section. You can follow the syntax below to add JavaScript code using the script tag. <script> // JavaScript code </script> In the following section, we will see how we can place JavaScript in an HTML file in different ways. JavaScript in <head>…</head> section If you want to have a script run on some event, such as when a user clicks somewhere,then you will place that script in the head as follows − <html> <head> <script type = “text/javascript”> function sayHello() { alert(“Hello World”) } </script> </head> <body> <input type = “button” onclick = “sayHello()” value = “Say Hello” /> </body> </html> JavaScript in <body>…</body> section If you need a script to run as the page loads so that the script generates content in the page, then the script goes in the <body> portion of the document. In this case, youwould not have any function defined using JavaScript. Take a look at the following code. <html> <head> </head> <body> <script type = “text/javascript”> document.write(“Hello World”) </script> <p>This is web page body </p> </body> </html> JavaScript in <body> and <head> Sections You can put your JavaScript code in <head> and <body> sections altogether as follows − <html> <head> <script type = “text/javascript”> function sayHello() { alert(“Hello World”) } </script> </head> <body> <script type = “text/javascript”> document.write(“Hello World”) </script> <input type = “button” onclick = “sayHello()” value = “Say Hello” /> </body> </html> JavaScript in External File As you begin to work more extensively with JavaScript, you will likely find cases where you are reusing identical JavaScript code on multiple pages of a site. You are not restricted to be maintaining identical code in multiple HTML files. The script tag provides a mechanism to allow you to store JavaScript in an external file and then include it in your HTML files. To use JavaScript from an external file source, you need to write all your JavaScript source code in a simple text file with the extension “.js” and then include that file as shown below. For example, you can keep the following content in the filename.js file, and then you can use the sayHello function in your HTML file after including the filename.js file. filename.js function sayHello() { alert(“Hello World”) } External JavaScript file doesn’t contain the <script> tag. Here is an example to show how you can include an external JavaScript file in your HTML code using the script tag and its src attribute. You may include the external script reference within the <head> or <body> tag. <html> <head> <script type = “text/javascript” src = “filename.js” ></script> </head> <body> … </body> </html> Also, you can create different modules to maintain code better and import each module in another JavaScript file or import all modules in a single HTML file. You can follow the below code to add multiple scripts into a single HTML file. <head> <script src = “filename1.js” ></script> <script src = “filename2.js” ></script> <script src = “filename3.js” ></script> </head> External References You can add an external JavaScript file in the HTML using the below 3 ways. 1. Using the full file path When you need to add any hosted JavaScript file or a file that doesn’t exists in the same project into the HTML, you should use the full file path. For example, <head> <script src = “C://javascript/filename.js” ></script> </head> 2. Using the relative file path If you are working on the project and JavaScript and HTML both files are in different folders, you can use the relative file path. <head> <script src = “javascriptfilename.js” ></script> </head> 3. Using the filename only If HTML and JavaScript both files are in the same folder, you can use the file name. <head> <script src = “filename.js” ></script> </head> Advantages of using the <script> tag Here are the advantages of using the <script> tag to add JavaScript in the HTML. Ease of Integration The <script> tag allows developers to integrate JavaScript into the HTML file easily. Adding JavaScript to the HTML file allows you to add behavior and interactivity to the web page. Immediate Execution Whenever the browser finds a <script> tag on the web page, it immediately executes the JavaScript code defined inside that. It enables website visitors to interact with the web pages and get real-time updates immediately. Inline and External scripts You can use the <script> tag to add the inline or external script into the HTML file. If you want to load JavaScript before the HTML of a web page, you can add the <script. Tag in the <head> tag. Otherwise, you can add the <script> tag in the <body> tag. External Libraries and Frameworks integration The <script> tag enables you to add external libraries and frameworks to the HTML web page. For example, in the below code, we have added JQuery to the web page using its CDN. <script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js”> </script> Here, the “src” attribute contains the hosted link to the library. Global Scope Access Whatever code you define in the script tag has access to the global scope of the web page. You can access the global variables, functions, etc., anywhere in the code. Print Page Previous Next Advertisements ”;