Variable Declaration
Site: | Philippine Science High School - MC - Knowledge Hub |
Course: | SY25.CS3.Web Development |
Book: | Variable Declaration |
Printed by: | , Guest user |
Date: | Thursday, 7 August 2025, 9:56 AM |
1. Introduction
After completing this module, you are expected to:
- Know the keywords in JavaScript
- Incorporating/embedding JavaScript inside the HTML documents
In this learning guide, we are going to focus on the “variable” which is one of the foremost
fundamental units of JavaScript. The different ways in which a variable can be declared and assigned,
as well as a few other common bits of information about variables can also be learned from this
module.
2. JavaScript Variables
JavaScript has variables just like many other programming languages. Variables are also
known as holders or containers. These containers will allow you to position data and then basically
refer to the data by naming the container.
Variables can be known as something that may change. A number defined by a letter is called
a variable in basic algebra. X might be a common name for a variable, but Y, Z, or another name may
describe it just as easily.
There is no value or meaning to x but a value can be added to it.
x = 5;
presently, x reflects 5. Consider x, which is a number, to be a container that stores 5.
In JavaScript, variables work the same, but they will be worth more than just a number. All
kinds of data values can be used, which you will understand by the end of this learning guide.
To declare a new variable in JavaScript we can use the keywords; var, let and const.
2.1. Using var keyword
var keyword is used to create and declare a variable. To construct a JavaScript statement, you
can refer to our example below. It is possible to reassign or redefine the values of the
variables.
var x; // without initializing
var x = 5; // initialize with a number
- <!DOCTYPE html>
- <html>
- <body>
- <h2>Variables of JavaScript</h2>
- <p>x is described as a variable in this example. Then, the value of x is assigned to 5: </p>
- <script>
- var x=5;
- document.write(x);
- </script>
- </body>
- </html>
The following outcome will result in this:
Determining what we have learned so far, the statement declaring a variable (x), using a
single equal sign, assigns a number data type (5) then followed by a semicolon (;).
A variable can change as it was used the first time and was declared with var.
var x = 5; // x was worth 5
x = 6; // now it’s worth 6
The variable holds one value at a time, and because the program runs from top to bottom, x
has now a value of 6.
Refer to this example of a variable that has a different type of data:
- <html>
- <body>
- <h2>JavaScript Variables</h2>
- <script>
- var greeting = "Oh hi Pisay";
- document.write(greeting);
- </script>
- </body>
- </html>
The greeting variable now includes the string Oh hi Pisay!
Multiple variables can be declared in a single line, separating them with commas.
var x = 5, var greeting = "Oh hi Pisay",…;
or variables could also be defined like below:
var x=y=z=5;
wherein x, y and z will all have 5 as their initial value.
Refer to the given example:
- <html>
- <body>
- <script>
- var x = 5;
- document.write("The value of variable is: " + x);
- document.write("</br>After redeclaration,</br>");
- var greeting = "Oh hi Pisay";
- document.write("The value of variable is: " + greeting);
- </script>
- </body>
- </html>
Before program execution, all the declarations in JavaScript (including variable declarations)
are processed. In this way, declaring a variable anywhere is equivalent to declaring it at the top of the
code. This provides JavaScript with the functionality to use the variables before their declarations
within the code. We call this behavior of variables “var hoisting”.
It is always recommended in programming to declare the variables before using them. This is
to avoid unintentional redeclaration of a variable.
This type of variable declaration method is never used by programmers. Other two methods
you need to consider are either let or const for your variables.
2.2. Using let
let variables are declared in a similar manner to var declared variables. When we use the let
keyword rather than var; it imposes scope constraints. The let declared variables cannot be redeclared.
This will give you a SyntaxError if you will try to do so. The scope of those variables is the block
they are defined in, also in any sub-blocks. The browser will throw a ReferenceError if you are trying
to access these variables outside of their block.
let x; // without initializing
let x = 5; // initialize with a number.
2.3. Naming Variables in JavaScript
Variable names in JavaScript are often referred to as identifiers. Identifiers are a sequence of
characters in a program that identifies a variable, function, or property.
Some key things to note about variables:
- Letters, numbers, a dollar sign ($), and an underscore (_) can be used for a variable name, but it cannot start or begin with a number.
- Any word on a list of reserved keywords as shown through this link https:// www.w3schools.com/js/js_reserved.asp, cannot be a variable
- It is case sensitive.
- The naming convention is camelCase, where a variable always starts in lowercase, but a capitalized letter begins with each subsequent word.
2.4. Using const
Much like variables defined using the let statement, constants are block-scoped. The const
declaration creates a constant whose scope is often either global or local to the declared block during
which we declare it. The value of a constant is read-only; you cannot change it through reassignment,
and you cannot redeclare it. An initializer for a constant is required; i.e., you want to specify its value
within the same statement in which it is declared (since you cannot alter it later). A function or a
variable within the same scope cannot have the same name as the variable.
Declaring your constants in uppercase is a good practice, because this may help programmers
differentiate the constants from other variables within the program.
Refer to the given example:
- <html>
- <body>
- <h2>Use const to declare a variable</h2>
- <script>
- var x = 5;
- const GREETING = "Hi, Pisay </br>";
- document.write(GREETING);
- document.write("The value of variable x is: " + x);
- </script>
- </body>
- </html>
3. Data Types
A data type is a data description. To communicate correctly with values, programming
languages need to have distinctive data types. With a number, you can do arithmetic, but not with a
word or sentence, because the computer classifies them in an unpredictable way. Six primitive
(fundamental) data types exist: strings, numbers, Boolean, null, undefined, and Symbol (new in
EcmaScript6). Primitives are able to hold a single value only. Another data type is an object which is
not one of these primitives and may contain multiple values. This learning guide will not cover the
discussion on object data type.
3.1. Strings
A string may be a series of characters.
A string will represent data that contains text. The name string possibly derived from software
engineers who were reminded of a string of beads.
- You should wrap it in double quotes (""):
"Pull the string, and it will follow wherever you wish."; //string with double quotation
- Or you wrap it in single quotes (' '):
'Pull the string, and it won’t happen anywhere at all.';//string with single quotation
But what if you need to write a single quoted string, or quote a double quoted string? Won’t the string break that?
It will and to tackle that there are choices. You can either use the opposite type of quotes
safely or by using the \ escape method:
"I’m a web designer, not a technician!". // Using single quotes inside a string of double quotes
'"Do. Or do not. There is no try. " – Yoda'; // Using double quote in a single string of quotes
"They call it an \"escape\" character"; // using \ escape character
We can apply string to a variable. Let us use our previous example.
var greeting = "Oh hi, Pisay";
Strings can also be joined together in a process known as concatenation. Variables and literal strings can be joined together by using the (+) plus symbol, concat function, and template literals.
Using (+) plus symbol:
var greeting = "Oh hi, "+ "Pisay"+ "!"; // displays Oh hi, Pisay!
Example:
- <!DOCTYPE html>
- <html>
- <body>
- <h2>Variables of JavaScript</h2>
- <script>
- var message = "Oh hi, ";
- var firstName = "Pisay ";
- var bam = "!";
- var greeting = message + firstName + bam; /* displays Oh hi, Pisay! */
- document.write(greeting);
- </script>
- </body>
- </html>
The example above shows that all the strings are represented by variables, and how the
different values in the three variables are combined using the plus (+) sign. This method could be used
in a system like if you have signed into an app (like your email) and are greeted with your name.
Using concat function
The concat function connects the calling string together, with arguments given and a new
string return.
The concat function joins together the calling string with arguments given, and a new string
is returned. The significant thing is that the string does not change but returns a new one.
Example:
var greetings = "Hello";
document.write (greetings.concat("Pisay")); // Hello Pisay
Using Template literals
Instead of double or single quotes, template literals are enclosed by the backtick (` `) (grave
accent) character. Expressions inserted as part of the string surrounded by a dollar sign and curly
brackets, may be evaluated.
Example:
var name = "Pisay";
var myCondition = "good";
document.write(`Hello ${name}! You're looking ${myCondition} today!`); // returns Hello Pisay! You’re looking good today!
3.2. Numbers
A numerical value is a number.
As strings do, numbers are not associated with any special syntax. If you were to quote 5
(“5”), it would be a character in a string, not a number. It can be a decimal (float) or a whole and it
can have positive or negative value.
var x = 5; // whole integer
var y = 1.2; // float
var z = -76; // negative whole integer
Number can be up to 15 digits.
var largeNumber = 999999999999999; // a valid number
How to write scientific notation in JavaScript?
- e-notation indicates a floating-point value.
- E-notation displays a number raised to a given control that should be multiplied by 10.
- In JavaScript, the format of e-notation is to have a number, integer or floating-point, followed by e or E, then by the power to multiply by 10.
Example:
var floatNum = 7.215e7; //equal to 72150000 document.write(floatNum);
In this case, 72,150,000 is equal to floatNum. In short, the notation states, "Take 7.215
and multiply it by 10^7."
With numbers: addition (+), subtraction (-), division (/) and multiplication (+), you can do
regular math.
var sum = 2 + 5; // displays 7
var difference = 6 – 4 // displays 2
With variables, you can do math like the example below:
- <!DOCTYPE html>
- <html>
- <body>
- <h2>Variables of JavaScript</h2>
- <script>
- var score1 = 3;
- var score2 = 7;
- var score3 = 9;
- var score4 = 1;
- var TotalScore = score1+score2+score3+score4; //displays 20
- document.write(TotalScore);
- </script>
- </body>
- </html>
Two uncommon number type:
While theoretically it’s a type of number, NaN means Not a Number. NaN is the product of
attempting to do arithmetic with other data types.
var notNum = 5 / "Five" // results NaN
For instance, dividing a number by a string will result in NaN.
Technically, Infinity is a number, either the answer of dividing by 0 or calculating a number too large.
var endless = 1 / 0; // results Infinity
3.3. Boolean
It is either true or false as a value.
In programming, Boolean values are exceptionally widely used for when a value can change
between yes or no, on and off, or true and false, Boolean values are exceptionally commonly used in
programming. Booleans will express the current state of anything which is likely to change.
We might use a Boolean, for example to show whether or not a checkbox is verified.
var IsChecked= true;
Booleans are often used to check whether two things are similar or whether a math conditions
result is true or false.
/* Verify if 7 is greater than 8 */
7 > 8; // results false
/* Verify if a variable is equal to a string */
var favcolor = "Blue";
favcolor === "Blue"; // results true
3.4. Undefined
There’s no value to an undefined variable.
We are declaring a variable, by using the var keyword, but it is undefined before a value is assigned to it.
var OneThing; // results undefined
It is still undefined if you do not declare the variable with var.
typeof anotherThing; // results undefined
3.5. null
null is a value where nothing is represented
null is the deliberate non-appearance of any value. It is that which does not exist and it’s not any of the other data types.
var empty = null;
Distinction is very subtle between null and undefined; but the most distinct distinction is that
a deliberately empty value is null.
3.6. Symbol
Symbol could be a data type that is unique and unchanging.
This may be a new primitive type of data that was generated with the most recent release of
JavaScript (EcmaScript6). The key advantage of each symbol is that unlike other data types that can
be overwritten, each symbol can be a completely unique token
We will not go into further detail since it is an advanced and little-used type of data, but
knowing that it exists is helpful.
var MySym = Symbol();
4. Summary and References
In summary,
- Variables can be thought of as named holders or containers.
- var keyword is used to create and declare a variable.
- let variables are declared in a similar manner to var declared variables. But we use the let keyword rather than var; this has scope constraints. The let declared variables cannot be redeclared.
- The const declaration creates a constant whose scope is often either global or local to the declared block during which we declare it. The value of a constant is read-only; you cannot change it through reassignment, and you can’t redeclare it.
- A data type is a data description. To communicate correctly with values, programming languages need to have distinctive data types. ● There are six primitive (fundamental) data types:
- String a series of characters.
- Number is a numerical value.
- Two other uncommon number types
- Theoretically NaN is a type of number, NaN means Not a Number. NaN is the product of attempting to do difficult arithmetic with other data types.
- Infinity is also a type of number, either the answer of dividing by 0 or calculating too large a number.
- Boolean is considered a value that is either true or false.
- An undefined variable has no value.
- null is a value that represents nothing.
- A Symbol could be a special and unchanging data type.
References:
JavaScript Escape Characters(n.d.). Quackit Tutorials. https://www.quackit.com/javascript/tutorial/ javascript_escape_characters.cfm
JavaScript tutorial. (n.d.). Programming Tutorials and Source Code Examples. http:// www.java2s.com/Tutorials/Javascript/index.htm
JavaScript tutorial (n.d.) W3Schools Online Web Tutorials. https://www.w3schools.com/js/DEFAULT.asp
JavaScript Variables (n.d.). RxJS, ggplot2, Python Data Persistence, Caffe2, PyBrain, Python Data Access, H2O, Colab, Theano, Flutter, KNime, Mean.js, Weka, Solidity. https:// www.tutorialspoint.com/javascript/javascript_variables.htm
Js 101. (n.d). Girl develop It SF - Teaching Materials. https://www.teaching-materials.org/javascript/
Rascia, T. (2017, January 31) A Beginner’s Guide to JavaScript Variables and Datatypes - SitePoint. SitePoint- Learn HTML, CSS, JavaScript, PHP, Ruby & Responsive Design. https:// www.sitepoint.com/beginners-guide-javascript-variables-and-datatypes/