JavaScript – Syntax ”; Previous Next JavaScript Syntax JavaScript syntax comprises a set of rules that define how to construct a JavaScript code. JavaScript can be implemented using JavaScript statements that are placed within the <script>… </script> HTML tags in a web page. You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags. The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. A simple syntax of your JavaScript will appear as follows. <script …> JavaScript code </script> The script tag takes two important attributes − Language −This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute. Type −This attribute is what is now recommended to indicate the scripting language in use and its value should be set to “text/javascript”. JavaScript has become default lannguage in HTML5, and modern browsers, so now adding type is not required. So your JavaScript segment will look like − <script language = “javascript” type = “text/javascript”> JavaScript code </script> Your First JavaScript Code Let us take a sample example to print out “Hello World”. We call document.write method which writes a string into our HTML document. This method can be used to write text, HTML, or both. Take a look at the following code − <html> <head> <title> Your first JavaScript program </title> <head> <body> <script language = “javascript” type = “text/javascript”> document.write(“Hello World!”) </script> </body> </html> This code will produce the following result − Hello World! JavaScript Values In JavaScript, you can have two types of values. Fixed values (Literals) Variables (Dynamic values) JavaScript Literals In the below code, 10 is a Number literal and ‘Hello’ is a string literal. <html> <body> <script> document.write(10); // Number Literal document.write(“<br />”); // To add line-break document.write(“Hello”); // String Literal </script> </body> </html> This code will produce the following result − 10 Hello JavaScript Variables In JavaScript, variables are used to store the dynamic data. You can use the below keyword to define variables in JavaScript. var let const You can use the assignment operator (equal sign) to assign values to the variable. In the below code, variable a contains the numeric value, and variable b contains the text (string). <html> <body> <script> let a = 5; // Variable Declaration document.write(a); // Using variable document.write(“<br>”); let b = “One”; document.write(b); </script> </body> </html> This code will produce the following result − 5 One Whitespace and Line Breaks JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand. Semicolons are Optional Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your statements are placed on a separate line. For example, the following code could be written without semicolons. <script> var1 = 10 var2 = 20 </script> But when formatted in a single line as follows, you must use semicolons − <script> var1 = 10; var2 = 20; </script> It is a good programming practice to use semicolons. Case Sensitivity JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters. So the identifiers Time and TIME will convey different meanings in JavaScript. In the code below, we compare the ‘time’ and ‘Time’ strings, which returns false. <html> <body> <script> let a = “time”; let b = “Time”; document.write(“a == b? ” + (a == b)); </script> </body> </html> This code will produce the following result − a == b? false Care should be taken while writing variable and function names in JavaScript. JavaScript and Camel Case Pascal Case − We can create variables like SmartWatch, MobileDevice, WebDrive, etc. It represents the upper camel case string. Lower Camel Case − JavaScript allows developers to use variable names and expression names like smartwatch, mobileDevice, webDriver, etc. Here the first character is in lowercase. Underscore − We can use underscore while declaring variables like smart_watch, mobile_device, web_driver, etc. JavaScript doesn’t allow adding the hyphen in variable name or expression name. JavaScript Keywords JavaScript contains multiple keywords which we can use for a particular task. For example, the function keyword can be used to define the function. The let, var, and const keywords can be used to define variables. Let’s understand the use of the keyword via the example below. Example In this example, we used the function keyword to define the function. We used the var keyword inside the function to define the sum variable. Also, we used the let and const keywords outside the function to define two variables and initialize them with values. After that, we called the function using the function name and passed variables as an argument. <html> <body> <script> function getSum(first, second) { var sum = first * second; document.write(“The product of ” + first + ” and ” + second + ” is ” + sum); } let first = 3; const second = 4; getSum(first, second); </script> </body> </html> This code will produce the following result − The product of 3 and 4 is 12 JavaScript doesn’t allow to use the of keywords as a variable or expression name. JavaScript Identifiers In JavaScript, identifiers are the name of variables, functions, objects, etc. For example, p is an identifier in the below code. <script> pet p = 90; </script> The ”test” is an identifier in the below code. <script> function test() { } </script> Here are the rules which you should follow to define valid
Category: javascript
JavaScript – Data Types
JavaScript – Data Types ”; Previous Next JavaScript Data Types Data types in JavaScript referes to the types of the values that we are storing or working with. One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language. JavaScript data types can be categorized as primitive and non-primitive (object). JavaScript (ES6 and higher) allows you to work with seven primitive data types − Strings of text e.g. “This text string” etc. Numbers, eg. 123, 120.50 etc. Boolean e.g. true or false. null undefined BigInt Symbol BigInt and Symbol are introduced in ES6. In ES5, there were only five primitive data types. In addition to these primitive data types, JavaScript supports a composite data type known as object. We will cover objects in detail in a separate chapter. The Object data type contains the 3 sub-data types − Object Array Date Why are data types important? In any programming language, data types are important for operation manipulation. For example, the below code generates the “1010” output. let sum = “10” + 10; Here, the JavaScript engine converts the second operand to a string and combines it using the ”+” operator rather than adding them. So, you need to ensure that the type of operands is correct. Now, let”s learn about each data type with examples. JavaScript String In JavaScript, the string is a sequence of characters and can be created using 3 different ways given below − Using the single quote Using the double quote Using the backticks Example In the example below, we have created strings using single quotes, double quotes, and backticks. In the output, it prints the same result for all 3 strings. <html> <head> <title> JavaScript string </title> </head> <body> <script> let str1 = “Hello World!”; // Using double quotes let str2 = ”Hello World!”; // Using single quotes let str3 = `Hello World!`; // Using backticks document.write(str1 + “<br>”); document.write(str2 + “<br>”); document.write(str3 + “<br>”); </script> </body> </html> JavaScript Number 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. Example In the example below, we demonstrate JavaScript numbers with and without decimal points. <html> <head> <title> JavaScript number </title> </head> <body> <script> let num1 = 10; // Integer let num2 = 10.22; // Floating point number document.write(“The value of num1 is ” + num1 + “<br/>”); document.write(“The value of num2 is ” + num2); </script> </body> </html> Example (Exponential notation of numbers) JavaScript also support exponential notaion of numbers. We have explained this in the below example code − <html> <head> <title> JavaScript number Exponential notation </title> </head> <body> <script> let num1 = 98e4; // 980000 let num2 = 98e-4; // 0.0098 document.write(“The value of num1 is: ” + num1 + “<br/>”); document.write(“The value of num2 is: ” + num2); </script> </body> </html> JavaScript Boolean In JavaScript, the Boolean data type has only two values: true or false. <html> <head> <title> JavaScript Boolean </title> </head> <body> <script> let bool1 = true; let bool2 = false; document.write(“The value of the bool1 is ” + bool1 + “<br/>”); document.write(“The value of the bool2 is ” + bool2 + “<br/>”); </script> </body> </html> JavaScript Undefined When you declare a variable but don”t initialize it, it contains an undefined value. However, you can manually assign an undefined value to the variable also. <html> <head> <title> JavaScript Undefined </title> </head> <body> <script> let houseNo; // Contains undefined value let apartment = “Ajay”; apartment = undefined; // Assigning the undefined value document.write(“The value of the house No is: ” + houseNo + “<br/>”); document.write(“The value of the apartment is: ” + apartment + “<br/>”); </script> </body> </html> JavaScript Null When any variable”s value is unknown, you can use the null. It is good practice to use the null for the empty or unknown value rather than the undefined one. <html> <head> <title> JavaScript null </title> </head> <body> <script> let houseNo = null; // Unknown house number let apartment = “B-2”; appartment = null; // Updating the value to null document.write(“The value of the houseNo is: ” + houseNo + “<br/>”); document.write(“The value of the apartment is: ” + apartment + “<br/>”); </script> </body> </html> JavaScript Bigint JavaScript stores only 64-bit long floating point numbers. If you want to store a very large number, you should use the Bigint. You can create Bigint by appending n to the end of the number. <html> <head> <title> JavaScript Bigint </title> </head> <body> <script> let largeNum = 1245646564515635412348923448234842842343546576876789n; document.write(“The value of the largeNum is ” + largeNum + “<br/>”); </script> </body> </html> JavaScript Symbol The Symbol data type is introduced in the ES6 version of JavaScript. It is used to create unique primitive, and immutable values. The Symbol() constructor can be used to create a unique symbol, and you may pass the string as a parameter of the Symbol() constructor. Example In the example below, we created the sym1 and sym2 symbols for the same string. After that, we compared the value of sym1 and sym2, and it gave a false output. It means both symbols are unique. <html> <head> <title> JavaScript Symbol </title> </head> <body> <script> let sym1 = Symbol(“123”); let sym2 = Symbol(“123”); let res = sym1 === sym2; document.write(“Is sym1 and Sym2 are same? ” + res + “<br/>”); </script> </body> </html> JavaScript Object In JavaScript, the object data type allows us to store the collection of the data in the key-value format. There are multiple ways to define the object, which we will see in the Objects chapter. Here, we will create an object using the object literals. Example In the example below, we used the ”{}” (Object literals) to create an obj object. The object contains the ”animal” property with the string value, the
JavaScript – Features
Javascript – Features ”; Previous Next JavaScript Features JavaScript is a highly popular and widely-used programming language for web development. It has a variety of features that make it powerful and flexible. Some of these features include being dynamic, lightweight, interpreted, functional, and object-oriented. Many open-source JavaScript libraries are available, facilitating the utilization of JavaScript in both frontend as well as backend development. Let”s highlight some of the key features of JavaScript. Easy Setup We don’t need a particular editor to start writing the JavaScript code. Even anyone can write JavaScript code in NotePad. Also, JavaScript can be executed in the browser without any interpreter or compiler setup. You can use the <script > tag to add JavaScript in the HTML file. However, it also allows you to add JavaScript to the web page from the external JavaScript file, having ”.js” extension. Browser Support All browsers support JavaScript, as all modern browser comes with the built-in JavaScript execution environment. However, you can also use the ‘window’ object to check whether the browser supports JavaScript or its particular feature. Dom Manipulation JavaScript allows developers to manipulate the webpage elements. Also, you can control the browser. It contains the various methods to access the DOM elements using different attributes and allows to customize the HTML elements. Event Handling JavaScript allows you to handle the events used to interact with the web page. For example, you can detect the mouse click on a particular HTML element using JavaScript and interact with the HTML element. Some other events also exist, like detecting the scrolling behavior of web page, etc. We will explore all events in the ‘JavaScript events’ chapter. Dynamic Typing JavaScript decides the type of variables at runtime. So, we don’t need to care about variable data type while writing the code, providing more flexibility to write code. Also, you can assign the values of the different data types to a single variable. For example, if you have stored the number value of a particular variable, you can update the variable’s value with the string. Functional Programming JavaScript supports the functional programming. In JavaScript, you can define the first-class function, pure functions, closures, higher-order functions, arrow funcitons, function expresions, etc. It mostly uses the functions as a primary building blocks to solve the problem. Cross-platform Support Each operating system and browser support JavaScript. So, it is widely used for developing websites, mobile applications, games, desktop applications, etc. Object-oriented Programming JavaScript contains the classes, and we can implement all object-oriented programming concepts using its functionality. It also supports inheritance, abstraction, polymorphism, encapsulation, etc, concepts of Object-oriented programming. Built-in Objects JavaScript contains built-in objects like Math and Date. We can use a Math object to perform mathematical operations and a Date object to manipulate the date easily. However, you can also manipulate the functionality of the built-in object. Object Prototypes In JavaScript, everything is an object. For example, array, function, number, string, boolean, set, map, etc. are objects. Each object contains the prototype property, which is hidden. You can use the prototype property to achive inheritance or extend the functionality of class or object, by other object’s functionality. Global Object JavaScript contains the global object to access the variables which are available everywhere. To access global variables in the browser, you can use the window object, and in Node.js, you can use the ”global” keyword to access global variables. Recently, globalThis keyword is introduced to access the global variables, and which is supported by the most runtime environments. Built-in Methods JavaScript also contains the built-in methods for each object. Developers can use the built-in methods to write efficient and shorter codes. For example, the Array object contains the filter() method to filter array elements and the sort() method to sort the array. The String object contains the replace() method to replace text in the string, the trim() method to remove whitespaces from the string, etc. Modular Programming JavaScript allows you to write the code in different modules and connect them with the parent module. So developers can write maintainable code. By writing the code in a separate module, you can reduce the complexity of the code and reuse each module whenever you require. JSON JSON stands for JavaScript object notation. It is a widely used data format to exchange data between two networks. For example, server and client. JavaScript also supports the JSON format to store the data. Asynchronous Programming JavaScript is a single-threaded programming language. To execute your code faster, you can use asynchronous programming. You can use promises in JavaScript to write asynchronous code, allowing us to handle multiple tasks asynchronously. Even-driven Architecture The event-driven architecture of JavaScript allows developers to create interactive and responsive web applications by handling a large user base concurrently. Due to the vast features and applications of JavaScript, the front end of Facebook is built on JavaScript. Netflix is built using the ReactJS framework of JavaScript. Similarly, Amazon, PayPal, Airbnb, LinkedIn, Twitter, etc., are also built using JavaScript. Server-side Support The Node.js runtime environment of JavaScript is widely used to create the backend of the application, as javaScript can also be used to create servers. It allows you to create a scalable backend for the application. Print Page Previous Next Advertisements ”;
Javascript – Home
JavaScript Tutorial Table of content JavaScript Tutorial Why to Learn JavaScript? Applications of JavaScript Programming Who Should Learn JavaScript? Prerequisites to Learn JavaScript JavaScript Online Quizzes JavaScript Jobs Careers Opportunities in JavaScript JavaScript Frameworks and Libraries Online JavaScript Editor Frequently Asked Questions about JavaScript JavaScript Articles Job Search PDF Version Quick Guide Resources Discussion JavaScript Tutorial JavaScript is a lightweight, interpreted programming language. It is commonly used to create dynamic and interactive elements in web applications. JavaScript is very easy to implement because it is integrated with HTML. It is open and cross-platform. This JavaScript tutorial has been designed for beginners as well as working professionals to help them understand the basic to advanced concepts and functionalities of JavaScript. It covers most of the important concepts related to JavaScript such as operators, control flow, functions, objects, OOPs, Asynchronous JavaScript, Events, DOM manipulation and much more. Why to Learn JavaScript? JavaScript is a MUST for students and working professionals to become a great Software Engineer, especially when they are working in Web Development Domain. We will list down some of the key advantages of learning JavaScript− JavaScript is the most popular programming language in the world, making it a programmer”s great choice. Once you learn JavaScript, it helps you develop great front-end and back-end software using different JavaScript based frameworks like jQuery, Node.JS, etc. JavaScript is everywhere, it comes installed on every modern web browser and so to learn JavaScript, you really do not need any special environment setup. For example, Chrome, Mozilla Firefox, Safari, and every browser you know as of today, supports JavaScript. JavaScript helps you create really beautiful and crazy fast websites. You can develop your website with a console like look and feel and give your users the best Graphical User Experience. JavaScript usage has now extended to mobile app development, desktop app development, and game development. This opens many opportunities for you as JavaScript Programmer. Due to high demand, there is tons of job growth and high pay for those who know JavaScript. You can navigate over to different job sites to see what having JavaScript skills looks like in the job market. Great thing about JavaScript is that you will find tons of frameworks and Libraries already developed which can be used directly in your software development to reduce your time to market. JavaScript is in all over the world, and companies like Google, Meta, Microsoft, PayPal, LinkedIn, etc. also use JavaScript. Furthermore, JavaScript has more than 1.5 lakh libraries. It is also growing. A huge community of JavaScript is available on the internet with students, developers, and mentors. So anyone can easily get support. There could be 1000s of good reasons to learn JavaScript Programming. But one thing for sure, to learn any programming language, not only JavaScript, you just need to code, and code, and finally code until you become an expert. Applications of JavaScript Programming As mentioned before, JavaScript is one of the most widely used programming languages (Front-end as well as Back-end). It has its presence in almost every area of software development. I”m going to list few of them here: Client side validation − This is really important to verify any user input before submitting it to the server and JavaScript plays an important role in validating those inputs at front-end itself. Manipulating HTML Pages − JavaScript helps in manipulating HTML page on the fly. This helps in adding and deleting any HTML tag very easily using JavaScript and modify your HTML to change its look and feel based on different devices and requirements. User Notifications − You can use JavaScript to raise dynamic pop-ups on the webpages to give different types of notifications to your website visitors. Back-end Data Loading − JavaScript provides Ajax library which helps in loading back-end data while you are doing some other processing. This really gives an amazing experience to your website visitors. Presentations − JavaScript also provides the facility of creating presentations which gives website look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web-based slide presentation. Server Applications − Node JS is built on Chrome”s JavaScript runtime for building fast and scalable network applications. This is an event based library which helps in developing very sophisticated server applications including Web Servers. Machine learning − Developers can use the ML5.js library to complete the task related to machine learning. Game Developments − JavaScript contains multiple libraries and NPM packages to design graphics for the game. We can use HTML, CSS, and JavaScript with libraries to develop the games. Mobile applications − We can use frameworks like React Native to build feature-rich mobile applications. Internet of Things (IoT) − JavaScript is used to add functionality to devices like smartwatches, earbuds, etc. Data visualization − JavaScript contains the libraries like D3.js to visualize the data efficiently. The D3.js is also used to prepare high-quality charts to visualize the data. Cloud computing − We can use JavaScript in serverless computing platforms like Cloudflare and AWS lambda to write and deploy functions on the cloud. This list goes on, there are various areas where millions of software developers are happily using JavaScript to develop great websites and other software. Who Should Learn JavaScript? This JavaScript tutorial has been prepared for student as well as working professionals to help them understand the basic functionality of JavaScript to build dynamic web pages and web applications. Prerequisites to Learn JavaScript For this JavaScript tutorial, it is assumed that the reader has prior knowledge of HTML coding. It would help if the reader had prior exposure to object-oriented programming concepts and a general idea of creating online applications. JavaScript Online Quizzes This Javascript tutorial helps you prepare for technical interviews and certification exams. We have provided various quizzes and assignments to check your learning level. Given quizzes have multiple choice type of questions and their answers with short explanation. Following is a sample quiz, try to attempt any of the given answers: Show Answer
JavaScript – Switch Case
JavaScript – Switch Case ”; Previous Next The JavaScript switch case is a conditional statement is used to execute different blocks of code depending on the value of an expression. The expression is evaluated, and if it matches the value of one of the case labels, the code block associated with that case is executed. If none of the case labels match the value of the expression, the code block associated with the default label is executed. You can use multiple if…else…if statements, as in the previous chapter, to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable. Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation, and it does so more efficiently than repeated if…else if statements. Flow Chart The following flow chart explains a switch-case statement works. Syntax The objective of a switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used. switch (expression) { case condition 1: statement(s) break; case condition 2: statement(s) break; … case condition n: statement(s) break; default: statement(s) } break − The statement keyword indicates the end of a particular case. If the ”break” statement were omitted, the interpreter would continue executing each statement in each of the following cases. default − The default keyword is used to define the default expression. When any case doesn”t match the expression of the switch-case statement, it executes the default code block. Examples Let”s understand the switch case statement in details with the help of some examples. Example In the example below, we have a grade variable and use it as an expression of the switch case statement. The switch case statement is used to execute the different code blocks according to the value of the grade variable. For the grade ”A”, it prints the ”Good job” in the output and terminates the switch case statement as we use the break statement. <html> <head> <title> JavaScript – Switch case statement </title> </head> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); let grade = ”A”; output.innerHTML += “Entering switch block <br />”; switch (grade) { case ”A”: output.innerHTML += “Good job <br />”; break; case ”B”: output.innerHTML += “Passed <br />”; break; case ”C”: output.innerHTML += “Failed <br />”; break; default: output.innerHTML += “Unknown grade <br />”; } output.innerHTML += “Exiting switch block”; </script> </body> </html> Output Entering switch block Good job Exiting switch block Break statements play a major role in switch-case statements. Try the following example that uses switch-case statement without any break statement. Example: Without break Statement When we don”t use the ”break” statement with any case of the switch case statement, it continues executing the next case without terminating it. In the below code, we haven”t used the break statement with the case ”A” and ”B”. So, for the grade ”A”, it will execute the statement of cases A, B, and C, and then it will terminate the execution of the switch case statement. <html> <head> <title> JavaScript – Switch case statement </title> </head> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); let grade = ”A”; output.innerHTML += “Entering switch block<br />”; switch (grade) { case ”A”: output.innerHTML += “Good job <br />”; case ”B”: output.innerHTML += “Passed <br />”; case ”C”: output.innerHTML += “Failed <br />”; default: output.innerHTML += “Unknown grade <br />”; } output.innerHTML += “Exiting switch block”; </script> </body> </html> Output Entering switch block Good job Passed Failed Unknown grade Exiting switch block Example: Common Code Blocks Sometimes, developers require to execute the common code block for the multiple values of the expression. It is very similar to the OR condition in the if-else statement. In the below code, we execute the same code block for cases A and B, and C and D. You may try to change the value of the grade variables and observe the output. <html> <head> <title> JavaScript – Switch case statement </title> </head> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); var grade = ”C”; output.innerHTML += “Entering switch block <br />”; switch (grade) { case ”A”: case ”B”: output.innerHTML += “Passed <br />”; break; case ”C”: case ”D”: output.innerHTML += “Failed! <br />”; break; default: output.innerHTML += “Unknown grade <br />”; } output.innerHTML += “Exiting switch block”; </script> </body> </html> Output Entering switch block Failed! Exiting switch block Example: Strict Comparison The switch case statement compares the expression value with the case value using the strict equality operator. The ”num” variable contains the integer value in the code below. In the switch case statement, all cases are in the string. So, the code executes the default statement. <html> <head> <title> JavaScript – Switch case statement </title> </head> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); let num = 10; switch (num) { case ”10”: output.innerHTML += “10 Marks!”; break; case ”11”: output.innerHTML += “11 Marks!”; break; default: output.innerHTML += “Input is not a string!”; } </script> </body> </html> Output Input is not a string! Print Page Previous Next Advertisements ”;
JavaScript – Exponentiation Operator ”; Previous Next Exponentiation Operator The exponentiation operator in JavaScript is represented as **. The exponentiation operator takes two operands and returns the power of the first operand raised to the second. The exponentiation operator can also accept the variables of the BigInt data type as operands. Also, it follows the property of associativity, which means a**b**c and a**(b**c) expressions give the same result. The exponentiation operator evaluates the expression from right to left. Syntax We should follow the syntax below to use the exponentiation operator. let pow = x ** y; Return value It returns the result of raising the first operand (x) to the power of the second operand (y). Examples Let”s understand the exponentiation operator in details with the help of some examples. Example The example below defines the p and q variables containing the 2 and 3 values. After that, we used the exponentiation operator to get the PQ. In the output, you can observe the value of the ”pow” variable, which is 23, equal to 8. <html> <body> <div id = “output”></div> <script> let p = 2; let q = 3; let pow = p ** q; document.getElementById(“output”).innerHTML = “The value of p ** q: ” + pow; </script> </body> </html> It will produce the following result − The value of p ** q: 8 Example: Associativity of Exponentiation Operator This example demonstrates that the exponentiation operator follows the associativity property and evaluates the expression from right to left. Both expressions print the 6561 in the output, equal to the 38, where 8 equals the 23. <html> <body> <div id=”output”></div> <script> let p = 3; let q = 2; let r = 3; let pow1 = p ** q ** r; let pow2 = p ** (q ** r); document.getElementById(“output”).innerHTML = “pow1 = ” + pow1 + “<br>” + “pow2 = ” + pow2; </script> </body> </html> It will produce the following result − pow1 = 6561 pow2 = 6561 Example: Exponentiation operator with BigInt variables The below example demonstrates that the exponentiation operator can also be used with the bigint numbers. It returns the bigint value in the output. <html> <body> <div id = “output”></div> <script> let p = 10000000000000000000000000000n; let q = 2n; let pow = p ** q; document.getElementById(“output”).innerHTML = “pow = ” + pow; </script> </body> </html> It will produce the following result − pow = 100000000000000000000000000000000000000000000000000000000 Example: Exponentiation operator with non-numeric values When you use the non-numeric value as an operand of the exponentiation operator, it converts the value to numeric and returns the result. If the operand can”t be converted to the numeric value, it returns NaN in the output. Here, it converts the ”[]” to 0 and gives the correct result. The numeric value for the string ”2a” is NaN, so it prints the NaN in the output. If the array contains a single numeric element, it parses the element. Otherwise, it evaluates NaN if the array contains multiple elements. <html> <body> <div id = “output”></div> <script> const output = document.getElementById(“output”); let pow = 2 ** []; // Number([]) = 0 output .innerHTML = “10 ** [] = ” + pow + “<br>”; pow = [] ** 2; // Number([]) = 0 output.innerHTML += “[] ** 2 = ” + pow + “<br>”; pow = 2 ** [2]; // Number([2]) = 2 output.innerHTML += “10 ** [2] = ” + pow + “<br>”; pow = “2” ** 2; // Number(“2”) = 2 output.innerHTML += “2 ** 2 = ” + pow + “<br>”; pow = “2a” ** 2; // Number(“2a”) = NaN output.innerHTML += “2a ** 2 = ” + pow + “<br>”; pow = [2, 3] ** 2; // Number([2, 3]) = NaN output.innerHTML += “[2, 3] ** 2 = ” + pow + “<br>”; </script> </body> </html> It will produce the following result − 10 ** [] = 1 [] ** 2 = 0 10 ** [2] = 4 2 ** 2 = 4 2a ** 2 = NaN [2, 3] ** 2 = NaN The exponentiation operator is an alternative to the pow() method of the Math() object. Print Page Previous Next Advertisements ”;
JavaScript – Type Conversions ”; Previous Next JavaScript Type Conversions Type Conversions in JavaScript refer to the automatic or explicit process of converting data from one data type to another in JavaScript. These conversions are essential for JavaScript to perform operations and comparisons effectively. JavaScript variables can contain the values of any data type as it is a weakly typed language. There are two types of type conversion in JavaScript − Implicit type conversion Explicit type conversion The implicit type conversion is also known as coercion. Implicit Type Conversion When type conversion is done by JavaScript automatically, it is called implicit type conversion. For example, when we use the ”+” operator with the string and number operands, JavaScript converts the number to a string and concatenates it with the string. Here are some examples of the implicit type conversion. Converting to String (Implicit conversion) In this example, we used the ”+” operator to implicitly convert different values to the string data type. “100” + 24; // Converts 24 to string ”100” + false; // Converts false boolean value to string “100” + null; // Converts null keyword to string Please note that to convert a value to string using “+” operator, one operand should be string. Let”s try the example below, and check the output − <html> <head> <title>Implicit conversion to string </title> </head> <body> <script> document.write(“100” + 24 + “<br/>”); document.write(”100” + false + “<br/>”); document.write(“100” + null+ “<br/>”); document.write(“100” + undefined+ “<br/>”); </script> </body> </html> Converting to Number (Implicit conversion) When you use the string values containing the digits with the arithmetic operators except for the ”+” operator, it converts operands to numbers automatically and performs the arithmetic operation, which you can see in the example below. Boolean values are also gets converted to a number. ”100” / 50; // Converts ”100” to 100 ”100” – ”50”; // Converts ”100” and ”50” to 100 and 50 ”100” * true; // Converts true to 1 ”100” – false; // Converts false to 0 ”tp” / 50 // converts ”tp” to NaN Try the example below and check the output − <html> <head> <title> Implicit conversion to Number </title> </head> <body> <script> document.write((”100” / 50) + “<br>”); document.write((”100” – ”50”) + “<br>”); document.write((”100” * true) + “<br>”); document.write((”100” – false) + “<br>”); document.write((”tp” / 50) + “<br>”); </script> </body> </html> Converting to Boolean (Implicit conversion) When you use the Nullish (!!) operator with any variable, it implicitly converts its value to the boolean value. num = !!0; // !0 = true, !!0 = false num = !!1; // !1 = false, !!1 = true str = !!””; // !”” = true, !!”” = false str = !!”Hello”; // !”Hello” = false, !!”Hello” = true Null to Number (Implicit conversion) In JavaScript, the null represents the empty. So, null automatically gets converted to 0 when we use it as an operand of the arithmetic operator. let num = 100 + null; // Converts null to 0 num = 100 * null; // Converts null to 0 Undefined with Number and Boolean (Implicit conversion) Using the undefined with the ”number” or ”boolean” value always gives the NaN in the output. Here, NaN means not a number. <html> <head> <title> Using undefined with a number and boolean value </title> </head> <body> <script> let num = 100 + undefined; // Prints NaN document.write(“The value of the num is: ” + num + “<br>”); num = false * undefined; // Prints NaN document.write(“The value of the num is: ” + num + “<br>”); </script> </body> </html> Explicit Type Conversion In many cases, programmers are required to convert the data type of the variable manually. It is called the explicit type conversion. In JavaScript, you can use the constructor functions or built-in functions to convert the type of the variable. Converting to String (Explicit conversion) You can use the String() constructor to convert the numbers, boolean, or other data types into the string. String(100); // number to string String(null); // null to string String(true); // boolean to string Example You can use the String() constructor function to convert a value to the string.You can also use typeof operator to check the type of the resultant value. <html> <head> <title> Converting to string explicitly </title> </head> <body> <script> document.write(typeof String(100) + “<br/>”); document.write(typeof String(null)+ “<br/>”); document.write(typeof String(true) + “<br/>”); </script> </body> </html> We can also use the toString() method of Number object to convert number to string. const num = 100; num.toString() // converts 100 to ”100” Converting to Number (Explicit conversion) You can use the Numer() constructor to convert a string into a number. We can also use unary plus (+) operator to convert a string to number. Number(”100”); // Converts ”100” to 100 Number(false); // Converts false to 0 Number(null); // Converts null to 0 num = +”200″; // Using the unary operator However, you can also use the below methods and variables to convert the string into numbers. Sr.No. Method / Operator Description 1 parseFloat() To extract the floating point number from the string. 2 parseInt() To extract the integer from the string. 3 + It is an unary operator. Example You can use the Number() constructor function or unary (+) operator to convert a string, boolean, or any other value to a number. The Number() function also converts the exponential notation of a number to a decimal number. <html> <head> <title> Converting to string explicitly </title> </head> <body> <script> document.write(Number(“200”) + “<br/>”); document.write(Number(“1000e-2”) + “<br/>”); document.write(Number(false) + “<br/>”); document.write(Number(null) + “<br/>”); document.write(Number(undefined) + “<br/>”); document.write(+”200″ + “<br/>”); </script> </body> </html> Converting to Boolean (Explicit conversion) You can use the Boolean() constructor to convert the other data types into Boolean. Boolean(100); // Converts number to boolean (true) Boolean(0); // 0 is falsy value (false) Boolean(“”); // Empty string is falsy value (false) Boolean(“Hi”); // Converts string to boolean (true) Boolean(null); // null is falsy value (false) Example You can use the Boolean() constructor to convert values to the Boolean. All
JavaScript – Console.log()
JavaScript – Console.log() ”; Previous Next JavaScript console.log() method The console.log() is one of the most important methods in JavaScript. It is used to print the message in the web console. We can use the console.log() method to debug the code by printing the output in the console. For example, if the developer requests API and wants to check the data received as a response, they might use the console.log() method. Also, there are other use cases of the console.log() method. Syntax You can follow the syntax below to use the console.log() method − console.log(msg1, msg2, …, msgN); You can pass different messages (msg1, msg2, …,msgN) by separating them with a comma as a parameter of the console.log() method. Console.log() with client-sided JavaScript Whenever we use the console.log() method in the frontend code, it prints the output in the browser”s console. Here is shortcut to open the console in Chrome browser − Press Ctrl + Shift + J together on Windows/Linux and Cmd + Option + J on Mac. Most browsers have the same shortcut key to open the console. However, if you can’t open the console in any browser, you may search on Google. Alternatively, to open the Console, right click the mouse and follow Inspect -> Console options. Example In the example below, we have printed the “Hello World!” message using the console.log() method. Also, we defined two integer variables and used another console.log() method to print the sum of num1 and num2. Here, developers can observe how we have printed variables in the console. The example also demonstrates that we can perform addition, multiplication, etc. operations in the console.log() method parameter. <html> <head> <title> Console.log() method with HTML </title> </head> <body> <h3> Message is printed in the console </h3> <p> Please open the console before clicking “Edit & Run” button </p> <script> console.log(“Hello World!”); var num1 = 30; var num2 = 20; console.log(“The sum of “, num1, ” and “, num2, ” is: “, num1 + num2); </script> </body> </html> It will produce the following result in the Console − Hello World! The sum of 30 and 20 is: 50 Example In the example below, we have created the JavaScript object containing the name, domain, and description properties. We have printed the object in the web console using the console.log() method. In the console, we can see that it prints the object, and we can expand the object by clicking the arrow given at the start of the object to see the detailed information. <html> <head> <title> Console.log() method with HTML </title> </head> <body> <h3> Message is printed in the console </h3> <p> Please open the console before clicking “Edit & Run” button </p> <script> // Defining the object var obj = { website: “Tutorialspoint”, Domain: “www.tutorialspoint.com”, description: “This site is for learning.” }; console.log(obj); </script> </body> </html> It will produce the following result in the Console − {website: ”Tutorialspoint”, Domain: ”www.tutorialspoint.com”, description: ”This site is for learning.”} Console.log() with server-side JavaScript The console.log() method with the backend code prints the output in the terminal where the backend server is running. Example We have written the below code printing the ‘Hello World!’ message into the app.js file and using the ‘node app.js’ command in the terminal to run the server. It prints the message in the terminal that we can observe. let message = “Hello world!”; console.log(message); This will produce the follwing result − Hello world! You can use the console.log() method with frontend and backend code to debug the code by printing output in the console. Print Page Previous Next Advertisements ”;