Learn some important characteristics of JavaScript syntax in this section.
As mentioned in the previous chapter, JavaScript code can be written inside HTML Script Tags or in a separate file with .js extension.
Character Set
JavaScript uses the unicode character set, so allows almost all characters, punctuations, and symbols.
Case Sensitive
JavaScript is a case-sensitive scripting language. So, name of functions, variables and keywords are case sensitive. For example, myfunction and MyFunction are different, Name is not equal to nAme, etc.
Variables
In JavaScript, a variable is declared with or without the var keyword.
Example: JavaScript Statements
What is JavaScript
JavaScript statements are separated by a semicolon. However, it is not mandatory to end a statement with a semicolon, but it is recommended.
Example: JavaScript Statements
Whitespaces
JavaScript ignores multiple spaces and tabs. The following statements are the same.
Example: Whitespaces in JavaScript
Code Comments
A comment is single or multiple lines, which give some information about the current program. Comments are not for execution.
Write comment after double slashes // or write multiple lines of comments between /* and */
Example: Comment JavaScript Code
String
A string is a text in JavaScript. The text content must be enclosed in double or single quotation marks.
Example: String in JavaScript
Number
JavaScript allows you to work with any type of number like integer, float, hexadecimal etc. Number must NOT be wrapped in quotation marks.
Example: Numbers in JavaScript
Boolean
As in other languages, JavaScript also includes true and false as a boolean value.
Example: Booleans in JavaScript
Keywords
Keywords are reserved words in JavaScript, which cannot be used as variable names or function names.
The following table lists some of the keywords used in JavaScript.
JavaScript provides built-in global functions to display messages to users for different purposes, e.g., displaying a simple message or displaying a message and take the user's confirmation or displaying a popup to take the user's input value.
Alert Box
Use the alert() function to display a message to the user that requires their attention. This alert box will have the OK button to close the alert box.
The alert() function takes a paramter of any type e.g., string, number, boolean etc. So, no need to convert a non-string type to a string type.
Confirm Box
Sometimes you need to take the user's confirmation to proceed. For example, you want to take the user's confirmation before saving updated data or deleting existing data. In this scenario, use the built-in function confirm().
The confirm() function displays a popup message to the user with two buttons, OK and Cancel. The confirm() function returns true if a user has clicked on the OK button or returns false if clicked on the Cancel button. You can use the return value to process further.
The following example demonstrates how to display a confirm box and then checks which button the user has clicked.
Prompt Box
Sometimes you may need to take the user's input to do further actions. For example, you want to calculate EMI based on the user's preferred tenure of the loan. For this kind of scenario, use the built-in function prompt().
Syntax: prompt([string message], [string defaultValue]);
The prompt() function takes two string parameters. The first parameter is the message to be displayed, and the second parameter is the default value which will be in input text when the message is displayed.
In the above example, the first parameter is a message, and the second parameter is "15" which will be shown to users by default. The prompt() function returns a user entered value. If a user has not entered anything, then it returns null. So it is recommended to check null before proceeding.
Note: The alert(), confirm(), and prompt() functions are global functions. So, they can be called using the window object e.g. window.alert(), window.confirm(), and window.prompt().
JavaScript Variables
Variable means anything that can vary. In JavaScript, a variable stores the data value that can be changed later on.
Use the reserved keyword var to declare a variable in JavaScript.
A variable must have a unique name. The following declares a variable.
var msg; // declaring a variable without assigning a value
Above, the var msg; is a variable declaration. It does not have any value yet. The default value of variables that do not have any value is undefined.
You can assign a value to a variable using the = operator when you declare it or after the declaration and before accessing it.
Example: Variable Initialization
var msg;
msg = "Hello JavaScript!"; // assigned a string value
alert(msg); // access a variable
//the following declares and assign a numeric value
var num = 100;
var hundred = num; // assigned a variable to varible
In the above example, the msg variable is declared first and then assigned a string value in the next statement. The num variable is declared and initialized with a numeric value in the same statement. Finally, the hundred variable is declared and initialized with another variable's value.
Multiple Variables Declaration
JavaScript allows multiple white spaces and line breaks when you declare a variable with var keyword.
Loosely-typed Variables
C# or Java has strongly typed variables. It means a variable must be declared with the data type that specifies the type of data a variable will store.
JavaScript is a loosely typed language. It means it does not require a data type to be declared. You can assign any literal values to a variable, e.g., string, integer, float, boolean, etc.
Example: Loosely Typed Variables
var myvariable = 1; // numeric value
myvariable = 'one'; // string value
myvariable = 1.1; // decimal value
myvariable = true; // Boolean value
myvariable = null; // null value
Variable Scope
In JavaScript, a variable can be declared either in the global scope or the local scope.
Global Variables
Variables declared out of any function are called global variables. They can be accessed anywhere in the JavaScript code, even inside any function.
Local Variables
Variables declared inside the function are called local variables to that function. They can only be accessed in the function where they are declared but not outside.
The following example includes global and local variables.
Example: Global and Local Variable
var greet = "Hello " // global variable
function myfunction(){
var msg = "JavaScript!";
alert(greet + msg); //can access global and local variable
}
myfunction();
alert(greet);//can access global variable
alert(msg); //error: can't access local variable
Declare Variables without the var Keyword
Variables can be declared and initialize without the var keyword. However, a value must be assigned to a variable declared without the var keyword.
The variables declared without the var keyword becomes global variables, irrespective of where they are declared. Visit Variable Scope in JavaScript to learn about it.
It is Not Recommended to declare a variable without var keyword because it can accidentally overwrite an existing global variable.
Javascript Operators
JavaScript includes operators same as other languages. An operator performs some operation on single or multiple operands (data value) and produces a result. For example, in 1 + 2, the + sign is an operator and 1 is left side operand and 2 is right side operand. The + operator performs the addition of two numeric values and returns a result.
JavaScript includes following categories of operators.
Arithmetic operators are used to perform mathematical operations between numeric operands.
The ++ and -- operators are unary operators. It works with either left or right operand only. When used with the left operand, e.g., x++, it will increase the value of x when the program control goes to the next statement. In the same way, when it is used with the right operand, e.g., ++x, it will increase the value of x there only. Therefore, x++ is called post-increment, and ++x is called pre-increment.
Example: Post and Pre Increment/Decrement
var x = 5;
x++; //post-increment, x will be 5 here and 6 in the next line
++x; //pre-increment, x will be 7 here
x--; //post-decrement, x will be 7 here and 6 in the next line
--x; //pre-decrement, x will be 5 here
......
String Concatenation
The + operator performs concatenation operation when one of the operands is of string type. The following example demonstrates string concatenation even if one of the operands is a string.
Example: + Operator with String
var a = 5, b = "Hello ", c = "World!", d = 10;
a + b; //returns "5Hello "
b + c; //returns "Hello World!"
a + d; //returns 15
b + true; //returns "Hello true"
c - b; //returns NaN; - operator can only used with numbers
Comparison Operators
JavaScript provides comparison operators that compare two operands and return a boolean value true or false.
Above, the 'script' src="/MyJavaScriptFile.js"> points to the external JavaScript file using the src="/MyJavaScriptFile.js" attribute where the value of the src attribute is the path or url from which a file needs to be loaded in the browser. Note that you can load the files from your domain as well as other domains.
The following example demonstrates the comparison operators.
Example: JavaScript Comparison Operators
var a = 5, b = 10, c = "5";
var x = a;
a == c; // returns true,
a === c; // returns false,
a == x; // returns true,
a != b; // returns true,
a > b; // returns false,
a < b; // returns true,
a >= b; // returns false,
a <= b; // returns true
,
Logical Operators
In JavaScript, the logical operators are used to combine two or more conditions. JavaScript provides the following logical operators.
Example: Logical Operators
var a = 5, b = 10;
(a != b) && (a < b); // returns true
(a > b) || (a == b); // returns false
(a < b) || (a == b); // returns true
!(a < b); // returns false
!(a > b); // returns true.
Example: Assignment operators
var x = 5, y = 10, z = 15;
x = y; //x would be 10
x += 1; //x would be 6
x -= 1; //x would be 4
x *= 5; //x would be 25
x /= 5; //x would be 1
x %= 2; //x would be 1.
Ternary Operator
? : ;
JavaScript provides a special operator called ternary operator :? that assigns a value to a variable based on some condition. This is the short form of the if else condition.
The ternary operator starts with conditional expression followed by the ? operator. The second part (after ? and before :) will be executed if the condition turns out to be true. Suppose, the condition returns false, then the third part (after :) will be executed.
Example: Ternary operator
var a = 10, b = 5;
var c = a > b? a : b; // value of c would be 10
var d = a > b? b : a; // value of d would be 5
Logical Operators
In JavaScript, the logical operators are used to combine two or more conditions. JavaScript provides the following logical operators.