Computer Programming in JavaScript
The Basics
(Unit 2)
Ogwal-Awio Kenneth
Lira University
2025
JavaScript Basics - Ogwal-Awio K., 2025 1
Unit learning outcomes
• By the end of this unit, the learners must be able to;
Explain the meaning of variable
Declare variables in JavaScript
Declare constants in JavaScript
Assign values to variables and constants in JavaScript
Implement the different variable scopes in JavaScript
Use JavaScript operators appropriately
Apply the concept of associativity in JavaScript
Apply operator precedence in JavaScript
Perform typecasting in JavaScript
JavaScript Basics - Ogwal-Awio K., 2025 2
Variable declarations
• A variable is a named storage space in memory for program data.
JS variables are dynamically typed
o It can store any type of JavaScript value
• We can declare variables to store data by using the var, let, or const
keywords.
o var – is an old way of declaring variables, although it still works.
o let – is a modern way of declaring variables.
o const – is like let, but the value stored cannot be changed through out the
program’s execution.
Variables should be named in a way that allows us to easily understand
what’s inside them.
JavaScript Basics - Ogwal-Awio K., 2025 3
Variable naming rules
• Variable names cannot be the same as for reserved keywords.
• Variable names are case-sensitive
• Variable names can only contain letters, digits, underscore (_), and dollar sign ($)
• Variable names must only start with a letter, an underscore or a dollar sign
• Variable names cannot contain spaces.
• Variable names must fit within one line
• By convention, JavaScript variable names are written in camelCase.
• By convention, JavaScript constant names are written in all-uppercase.
• By convention, variable names should be given descriptive names that relate to
their content and usage.
As JavaScript variables do not have set types, it can be useful to include an
indication of the typeJavaScript
in the name.
Basics - Ogwal-Awio K., 2025 4
Which is valid and which is not?
let camelCase = "lowercase letter, then uppercase"; ?
let dinner2Go = "pizza"; ?
let total% = 78; ?
let I_AM_HUNGRY = true; ?
let _Hello_ = "what a nice greeting“; ?
let 2fast2catch = "bold claim"; ?
let function = false; ?
let class = "easy"; ?
let $_$ = "money eyes"; ?
JavaScript Basics - Ogwal-Awio K., 2025 5
Which is valid and which is not? And why?
let camelCase = "lowercase letter, then uppercase"; Valid Correct syntactically and conventionally
let dinner2Go = "pizza"; Valid Correct syntactically and conventionally
let total% = 78; Invalid Incorrect syntactically
let I_AM_HUNGRY = true; Valid Correct syntactically and conventionally
let _Hello_ = "what a nice greeting“; Valid Correct syntactically and conventionally
let 2fast2catch = "bold claim"; Invalid Correct syntactically and conventionally
let function = false; Invalid Incorrect syntactically and conventionally
let class = "easy"; Invalid Incorrect syntactically and conventionally
let $_$ = "money eyes"; valid Correct syntactically and conventionally
JavaScript Basics - Ogwal-Awio K., 2025 6
Variable declaration using var
o var x = 50; //declaring and assigning a value
o var x = 60;
x + 72; //referencing it by variable name after declaring it
o var x = 70;
var y = x + 82; //using a variable while declaring another variable
alert(y);
o var weather = "rainy";
weather = "sunny"; //reassigning variables
alert(weather);
JavaScript Basics - Ogwal-Awio K., 2025 7
Variable declaration using let
o let message; //declaring a variable named message
o let message;
message = 'Hello'; // storing the string 'Hello' in message
o let message;
message = 'Hello!';
alert(message); // displaying the content of the variable
o let user = 'John', age = 25, message = 'Hello' // multiple declarations
JavaScript Basics - Ogwal-Awio K., 2025 8
Variable declaration using let…
o let city;
city = “Kampala”
city = “Lira”; // value changed
alert(city);
o let countryName = “Kenya”
let country;
country = countryName; // Copy Kenya from countryName into country
alert(countryName);
alert(country);
JavaScript Basics - Ogwal-Awio K., 2025 9
var vs let – the difference in practive
• The difference between let and var is in the scope of the variables they
create
Variables declared by let are only available inside the block where they're
defined.
Variables declared by var are available throughout the function in which
they're declared.
JavaScript Basics - Ogwal-Awio K., 2025 10
Variable declaration using const
• const is used to declare a constant
oA constant is a variable whose value does not change throughout the
program execution.
const MYBIRTHDAY = “18.04.2003”;
const HERBIRTHDAY = “12.04.2002”;
HERBIRTHDAY = “01.01.2004”; // error! Why the error?
JavaScript Basics - Ogwal-Awio K., 2025 11
Variable declaration using const…
const COLOR_RED = "#F00";
const COLOR_GREEN = "#0F0";
const COLOR_BLUE = "#00F";
const COLOR_ORANGE = "#FF7F00";
let color = COLOR_ORANGE; // ...when we need to pick a color
alert(color); // #FF7F00
JavaScript Basics - Ogwal-Awio K., 2025 12
Variable scope
• Scope in JavaScript refers to the accessibility or visibility of variables.
Which parts of a program can access a variable? or where is the variable visible?
• Scope is important because:
Security is enhanced as the variables are only accessed from a certain area of the
program and unintended modifications to the variables from other parts of the
program are avoided.
Namespace collisions are reduced since same variable names can be used in
different scopes.
• There are three variable scopes in JavaScript: Block scope, Function scope, and
Global scope
JavaScript Basics - Ogwal-Awio K., 2025 13
Block scope
• Is when a variable is declared inside a specific block and can't be accessed
outside of that block.
Variables declared inside a { } block cannot be accessed from outside it
var x = 1;
let y = 1;
if (true) {
var x = 2;
let y = 2;
}
[Link](x);// Expected output to the console: 2
[Link](y);// Expected output to the console: 1
• Block scopes are used in if statements, for statements, and the like.
JavaScript Basics - Ogwal-Awio K., 2025 14
Function scope
• Function scope is where variables that are declared inside a function and
are only accessible from anywhere within that function.
Also called local variables
Script Output
/* program showing local Hello LIT Gurus
scope of a variable */ Uncaught ReferenceError: b is not defined
let a = “hello”;
function greet() {
let b = “ LIT Gurus”
alert(a + b);
}
greet();
[Link](a + b);JavaScript Basics - Ogwal-Awio K., 2025 15
Global scope
• Is a variable declared at the top of a program or outside of a function.
The variable is available anywhere within the code.
They can be accessed by any function directly.
• The keyword used to declared does not matter they all behave the same
way.
• It is the default scope for variables and functions in JavaScript.
A variable declared without a keyword is also considered global even
though it is declared in the function.
JavaScript Basics - Ogwal-Awio K., 2025 16
Global scope – example
Script Output?
// program to print a text Hello Guys
let a = "hello guys";
function greet () {
[Link](a);
}
greet(); // function call
JavaScript Basics - Ogwal-Awio K., 2025 17
Class group discussion
Form TWO groups, and in your groups;
1. Discuss the difference between nested scope and lexical scope (GROUP 1)
2. Discuss the difference between scope chain and lexical environment (GROUP 2)
REQUIRED:
Send a copy of your work before that presentation time to akogwal@[Link]
JavaScript Basics - Ogwal-Awio K., 2025 18
Variable scope…
• If you forget to code the let keyword in a variable declaration, the
JavaScript engine assumes that the variable is global.
• Which causes debugging problems.
• The solution to this is hoisting!
JavaScript Basics - Ogwal-Awio K., 2025 20
Some thing to keep you busy
Discuss the concept of hoisting in JavaScript
JavaScript Basics - Ogwal-Awio K., 2025 25
Class adjourned till tomorrow…
JavaScript Basics - Ogwal-Awio K., 2025 25
Operators in JavaScript
• Operators are special symbols in JavaScript for carrying out arithmetic or
logical computations.
The constructs which can manipulate the values of operands.
• The value that the operator operates on is called the operand.
For example, consider 2+3
o + is the operator that performs addition.
o 2 and 3 are the operands, and
o 5 will be the output of the operation.
JavaScript Basics - Ogwal-Awio K., 2025 4
Operators in JavaScript…
• Operators are used to assign values, compare values, perform
arithmetic operations, and more...
• There are different types of JavaScript operators:
Assignment Operators
Arithmetic Operators
Comparison Operators
Logical Operators
Conditional Operators
Type Operators
JavaScript Basics - Ogwal-Awio K., 2025 5
Asignment operator
• The Assignment Operator (=) assigns a value to a variable:
• Examples:
// Assign the value 25 to x
let x = 25;
// Assign the value 12 to y
let y = 12;
// Assign the value x + y to z:
let z = x + y;
JavaScript Basics - Ogwal-Awio K., 2025 6
Compound assignment operators
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
JavaScript Basics - Ogwal-Awio K., 2025 7
Arithmetic operators in JavaScript
Using: x = 8 and y = 10
Symbol Operator Example Results
+ Addition x=y+2 y=10, x=12
- Subtraction x=y-2 y=10, x=7
* Multiplication x=y*2 y=10, x=20
** Exponentiation x=y**2 y=10, x=100
/ Division x=y/2 y=10, x=5
% Remainder x=y%2 y=10, x=0
++ Pre increment x = ++y y=11, x=11
++ Post increment x = y++ y=11, x=10
-- Pre decrement x = --y y=9, x=9
-- Post decrement x = y-- y=9, x=10
JavaScript Basics - Ogwal-Awio K., 2025 8
Comparison operators in JavaScript
Using: x = 8 and y = 10
Symbol Operator Example Results
=== Strictly equivalent
== Less strictly equivalent
!== Not equivalent (strictly)
!= Not equivalent (less strictly)
< Less than
> Greater than
<= Less than or equal too
>= Greater than or equal to
JavaScript Basics - Ogwal-Awio K., 2025 9
Logical operators
Using: x = 6 and y = 7
Operator Description Example
&& and (x < 10 && y > 1) is true
|| or (x == 5 || y == 5) is false
! not !(x == y) is true
LEFT RIGHT Logical AND Logical OR Logical NOT
LEFT AND RIGHT LEFT OR RIGHT NOT LEFT
True True True True False
True False False True False
False True False True True
False False False False True
JavaScript Basics - Ogwal-Awio K., 2025 10
Conditional operators
• JavaScript also contains a conditional operator that assigns a value to
a variable based on some condition.
• Example:
let canvote = (age > 18) ? “Old enough”:“Still young”;
JavaScript Basics - Ogwal-Awio K., 2025 11
Operator precedence
• JavaScript evaluates an expression according to a predefined order of
precedence.
Precedence helps the language engine to determine which part of the
expression to evaluate first, which to evaluate second, and so on.
This controls ordering problem.
JavaScript Basics - Ogwal-Awio K., 2025 34
14
Operator Operation Order of precedence Order of evaluation
++ Increment First Right to Left
-- Decrement First Right to Left
— Negation First Right to Left
! NOT First Right to Left
*, /, % Multiplication, division, modulus Second Left to Right
+, — Addition, subtraction Third Left to Right
+ Concatenation Third Left to Right
<, <= Less than, less than, or equal Fourth Left to Right
>, >= Greater than, greater than, or equal Fourth Left to Right
== Equal Fifth Left to Right
!= Not equal Fifth Left to Right
=== Identity Fifth Left to Right
!== Non-identity Fifth Left to Right
&& AND Sixth Left to Right
|| OR Sixth Left to Right
?: Ternary Seventh Right to Left
= Assignment Eighth Right to Left
+=, -=, and so on. Arithmetic assignmeDnattatypes,Operators and Keyw oE rdisgohftJh
avaScript - Ogwal-Awio
JavaScript Basics - Ogwal-Awio K., 2025 Right to Left 15
35
Associativity in JavaScript
• The associativity of an operator is the description of the direction
which the operations should get executed in within a statement.
• It is applied when statements contain operators that have the same
precedence.
• For example:
Both multiplication and division operators in JavaScript have left to right
associativity, while some operators may have right to left associativity.
JavaScript Basics - Ogwal-Awio K., 2025 16
Datatypes in JavaScript
• A datatypes is a characterization of a stored value
• It determines:
The kinds of values that can be stored
how the value is stored internally
The kinds of operations that can be applied
• Syntactic representation
It involves how the value is expressed in a program
• JavaScript has two categories of datatypes: primitive datatypes and
composite datatypes.
JavaScript Basics - Ogwal-Awio K., 2025 37
18
Datatypes in JavaScript
• The primitive types include:
String
Number
Bigint
Boolean
Undefined
Null
Symbol
• The non-primitive types include:
Object
Array
JavaScript Basics - Ogwal-Awio K., 2025 38
19
Strings
• A string is a series of characters with values are written with quotes.
You can use single or double quotes
• A string spans any length including the zero-length “null” string “ ”
• Operations on it include:
concatenation (+ operator)
output to the Web page
ousing alert(…)
Value is returned by the prompt() function
• Is enclosed in double or single quotes
JavaScript Basics - Ogwal-Awio K., 2025 20
Examples
let valr1; let val2;
val1 = “Hello”;
val2 = “there”;
let val3 = val1 + “ ” + val2;
alert(val3);
val4 = “45”;
val2 = val3 + val4;
alert(val2);
JavaScript Basics - Ogwal-Awio K., 2025 21
number
• Numerical values stored as whole number or decimal number.
Numbers can be written with, or without decimals
Extra large or extra small numbers can be written with scientific notation
E.g. in scientific notation: 1.2e3 = 1.2 x 103 = 1200
• Integer number is a whole numbers between -9223372036854775808
and 9223372036854775808
• Operations on integers include:
standard mathematical operations (+, -, *, /, etc.)
special math functions
Integer values are not placed within quotation marks.
JavaScript Basics - Ogwal-Awio K., 2025 22
Examples
let val1 = 45;
let val2 = 055;
let val3 = val1 + val2;
alert(val3);
JavaScript Basics - Ogwal-Awio K., 2025 23
Number datatype…
• Floating point number values range from ±1.0x10308 to ± 1.0x10-323
17 digits of precision (past decimal point)
• Operations on floating point numbers include:
standard mathematical operations
special math functions
• Floating point number values are unquoted
JavaScript Basics - Ogwal-Awio K., 2025 24
Examples
let val1 = 5.3;
let val2 = 5.3e1;
let val3 = val1 + val2;
alert(val3);
When adding a number and a string, JavaScript will treat the number
as a string.
JavaScript Basics - Ogwal-Awio K., 2025 25
Boolean
• Is a type that have two possible values: true or false .
Booleans are often used in conditional testing.
• Operations on Booleans are logical operations
• and &&
• or ||
• not !
• Syntax includes the value keywords (true, false)
JavaScript Basics - Ogwal-Awio K., 2025 27
Examples
let val5 = true;
let val1 = true;
let val6 = false;
let val2 = false;
let val7 = val5 II val6;
let val3 = val1 && !val2;
alert(val3);
alert(val3);
JavaScript Basics - Ogwal-Awio K., 2025 28
undefined value
• Undefined is a variable in JavaScript without a value.
Thus the name of its type
An undeclared variable is assigned the value undefined at execution.
• This is the value of a variable when it is created
if you use a variable without defining it, you get an error
• You can declare a variable without giving it a value
not an error
variable has no value
unexpected results
JavaScript Basics - Ogwal-Awio K., 2025 29
Other primitive Data types in JavaScript
• Bigint – a relatively new datatype that is used to store integer values that
are too big to be represented by a normal JavaScript Number datatype.
Introduced from ES2020.
• Null – is a special data type which can have only a null value.
A variable of data type NULL is a variable that has no value assigned to it.
• Symbol – is a type that represents a unique identifier.
Symbols are used to create object properties, e.g. to assign a unique
identifier to an object.
It is a built-in object whose constructor returns a symbol value that is
guaranteed to be unique.
JavaScript Basics - Ogwal-Awio K., 2025 30
Data types in JavaScript – composite types
• Object - JavaScript objects are written with curly braces { }.
Object properties are written as name:value pairs, separated by
commas.
Arrays – is a JavaScript object which enables storing a collection of
multiple items under a single variable name.
JavaScript Basics - Ogwal-Awio K., 2025 31
Commonly used Datatypes in JavaScript
JavaScript Basics - Ogwal-Awio K., 2025 32
Object datatype
• It is a non-primitive data type that consists of unordered key-value
pairs.
• An object is created with braces {…} with an optional list of properties.
A property is a “key: value” pair, where key is a string (also called a
“property name”), and value can be anything.
• Analogy: one can imagine an object as a cabinet with signed files –
where every piece of data is stored in its file by the key.
JavaScript Basics - Ogwal-Awio K., 2025 34
Object type…
• An empty object (“empty cabinet”) can be created using one of two syntaxes:
let user = new Object(); // "object constructor" syntax
let user = {}; // "object literal" syntax
Example:
let user = { // an object
name: “Cosmo", // by key "name" store value "Joel“
age: 22 // by key "age" store value 22
};
// to get property values of the object
alert( [Link] ); // Cosmos
alert( [Link] ); //JavaScript
22 Basics - Ogwal-Awio K., 2025 35
Object type – deleting a value
• To remove a property, we can use the delete operator:
delete [Link];
JavaScript Basics - Ogwal-Awio K., 2025 37
Object type – multiword property names
• Multiple words can be used as property names
The multiword property name must be quoted.
let user = {
name: "John",
age: 30,
"likes birds": true
};
JavaScript Basics - Ogwal-Awio K., 2025 38
Object type – “trailing” or “hanging” comma
• The last property in the list may end with a comma:
let user = {
name: "John",
age: 30,
};
• That is called a “trailing” or “hanging” comma.
This makes it easier to add/remove/move around properties, because
all lines become alike.
JavaScript Basics - Ogwal-Awio K., 2025 39
typeof operator
• typeof in JavaScript is an operator used for type checking and returns
the data type of the operand passed to it.
The operand can be any variable, function, or object whose type
you want to find out using the typeof operator.
• It returns a string indicating the type of the operand's value.
JavaScript Basics - Ogwal-Awio K., 2025 41
Typeof operator – examples
alert(typeof 42);
alert(typeof “blubber”);
alert(typeof true);
alert(typeof undeclaredVariable);
JavaScript Basics - Ogwal-Awio K., 2025 42
Type casting
• Typecasting in JavaScript means converting one data type to another
data type.
This is also known as type conversion or type coercion.
• There are two types of conversions:
Implicit type conversions, and
Explicit type conversions
JavaScript Basics - Ogwal-Awio K., 2025 43
Implicit type casting
• Is the automatic conversion due to or as an internal requirement by
the compiler or the interpreter.
Implicit type conversion takes place automatically when there is an
internal requirement for it.
o JavaScript automatically coerces a data type to another.
• Consider the example of the boolean values:
JavaScript will temporarily convert the value in parentheses to a
boolean to evaluate the if expression.
oThis is because JavaScript expects a boolean value in a conditional
expression.
JavaScript Basics - Ogwal-Awio K., 2025 44
Implicit type casting – example
let val = 1;
if (val) {
alert( “yes, val exists”);
}
The values 0, -0, empty string (NaN), undefined, and null, evaluate to
false and all other values evaluate to true, including empty arrays and
objects.
JavaScript Basics - Ogwal-Awio K., 2025 45
Implicit conversion with == operator
• Type conversion is also performed when comparing values using the
equal (==) and not equal (!=) operators.
• Example:
alert( 125 == “125”);
Implicit conversion is not performed when using the identical (===)
and not identical (!==) operators.
JavaScript Basics - Ogwal-Awio K., 2025 46
Explicit type casting
• This is done forcefully by the developer.
In JavaScript, this can be done only for strings, numbers and Boolean
(object) data types.
• This can be achieved via various built-in functions.
• Examples of the built-in functions:
o parseInt()
o parseFloat()
o toString()
o Number()
o etc.
JavaScript Basics - Ogwal-Awio K., 2025 47
Explicit type casting – example
let g = 9.8
alert(g)
alert(typeof g)
alert([Link]())
alert(typeof [Link]())
JavaScript Basics - Ogwal-Awio K., 2025 48
Numeric Typecasting
• To convert the given input to a number the Number() method is used.
It takes one parameter
o i.e., the input which is given to be converted to number.
The conversions can be done to float type or integer type.
• To convert it in to Integer type, parseInt() is used.
• To convert it in to Float type, parseFloat() is used.
• Syntax: Function_name(input)
JavaScript Basics - Ogwal-Awio K., 2025 49
Typecasting in Strings
• In JavaScript the strings are treated as objects.
So, here in string type casting anything like a number or a character given will
be converted to a string.
• The String() method is used to convert any given value to string.
The String() method will take one parameter, i.e., the input which is to be
converted to string.
JavaScript Basics - Ogwal-Awio K., 2025 51
Typecasting in Strings – examples
let input = 25
alert("The input value is:" + input + “and the type is ”+ typeof(input))
alert("Operation before typecasting with its type is:" + (10 + input), typeof((10 + input))) sInput = String(input)
alert("After the type casting is done the type is:" + sInput + typeof(sInput))
alert("The arithmetic operation after typecasting with its type is:" + (10 + sInput) + typeof(10 + sInput))
JavaScript Basics - Ogwal-Awio K., 2025 52
String typecasting…
let num1 = 5
String(num1) //what type of casting? Explicit casting
alert('10' + num1) //output is 105 not 15, why?Both 10 and value of num1 are strings, right?
If so, what happened to output 105, not 15?
Output 105 was due to string concatenation.
//more…
String(true) // ‘true’
String(false) // ‘false’
String(0) // ‘0’
String(-0.99) // ‘-0.99’
String(null) // “null”
String(undefined) // “undefined”
JavaScript Basics - Ogwal-Awio K., 2025 52
Boolean typecasting…
Explicit:
Boolean(0) //false
Boolean(null) //false
Boolean(undefined) //false
Boolean('') //false
Boolean('hi') //true
Boolean(-1.2) //true
Boolean(new Date()) //true
Implicit:
Boolean(2 || 'hello') //true
Boolean(0 && new Date()) //false
if(2) { ... } //true
Boolean(0 == '0') //true
Boolean(0 === '0') //false
JavaScript Basics - Ogwal-Awio K., 2025 52
Coersion vs Type Casting
• Implicit Type Conversion is also known, and more commonly referred
to, as Coercion
This is automatically done during code execution.
• Explicit Type Conversion is also known as Type Casting.
This is done by you the developer.
JavaScript Basics - Ogwal-Awio K., 2025 53
Try out…
• Create a program that converts user input between different data types, with the following options:
i. Convert integer to float
ii. Convert float to integer
iii. Convert string to integer
iv. Convert integer to string
v. Convert string to float
vi. Convert float to string
• The program should prompt for value and user should first select conversion type, then the converted
value is displayed.
NOTE: Use only built-in data types (int, float, and str), and explicit conversion functions.
REQUIRED:
Send the source code to akogwal@[Link] before the next lecture. Choosing at random, two students
will present their programs. JavaScript Basics - Ogwal-Awio K., 2025 53
Thank you
JavaScript Basics - Ogwal-Awio K., 2025 55