Page 336 - Webapplication11_C11_Flipbook
P. 336
JavaScript Variable Scope
In JavaScript, variable scope refers to where a variable is accessible within your code. The two main types of scope in
JavaScript are global scope and local scope.
Ð ÐGlobal Variables: These variables are declared outside of any function or block. They have global scope, meaning
they can be accessed from anywhere in the JavaScript code, including functions, blocks, and other parts of the
program. They are typically declared at the top of the script, and remain available throughout the execution of the
script.
ÐLocal Variables: These variables are declared within a function or block and have local scope. These variables
Ð
are only accessible within the function or block where they are defined. Function parameters are also considered
local variables within the function. Local variables are not accessible from outside the function in which they are
declared.
JavaScript Literals
In JavaScript, literals are fixed values that you directly write into your code. These values are not variables; they're
constant values that can be of various types.
JavaScript literals are foundational elements of the language, representing fixed, unchangeable values that are written
directly in your code. These values are distinct from variables, which can change during the execution of a program.
By using different types of literals, you can define various forms of data that are essential for representing numbers,
text, conditions, and collections.
Some different types of literals are as follows:
ÐNumber literals represent integers or floating-point numbers.
Ð
Ð ÐString literals hold textual data.
Ð ÐBoolean literals represent the binary true/false logic.
Ð ÐObject and array literals provide structured data formats.
Example:
var a = "Arabic Numbers"; // String literal
var b = 100; // Number literal (integer)
var x = 56.32; // Number literal (floating-point)
var c = [12, 24, 36]; // Array literal
var d = false; // Boolean literal
Concatenation of Variables
The + sign is used to concatenate variables and strings on the same line. When both operands are numbers, addition
is performed. When using the + operator in expressions involving numeric and string values, the two values are
concatenated or joined. Following examples shows the use of + sign:
var price = "The price of a pencil is " + 10;
// will display "The price of a pencil is 10"
var info = "I am " 16 + " years old.";
// will display "I am 16 years old."
If both the operands are numeric, then the + sign performs an addition operation.
Let us take an example:
Example: To calculate the sum of two numbers using JavaScript.
<HTML>
<BODY>
334 Touchpad Web Applications-XI

