Web Programming
Lecture 3

Introduction to JavaScript

Josue Obregon

Seoul National University of Science and Technology
Information Technology Management
Lecture slides index

March 14, 2025

Course structure

Roadmaps: Frontend, backend and fullstack

Agenda

JavaScript

  • A lightweight “scripting” programming language
  • Created in 1995 by Brendan Eich
    • Originally called Mocha, but it was renamed LiveScript and finally JavaScript
  • First version was called ECMAScript1 1 (ES1)
  • It releases versions every year (evolves fast)
  • Current version is ECMAScript 2024 (ES2024)
  • NOT related to Java other than by name and some syntactic similarities

Why are we learning JavaScript?

  • We can use JavaScript in frontend development to:
    • Insert dynamic text into HTML (e.g., username)
    • React to events (e.g., page load, user’s mouse click)
    • Retrieve information about a user’s computer (e.g., what browser they are using)
    • Request additional data needed for the page (e.g., from an API; more on this in a couple weeks)
  • Thanks to Node.js (a runtime environment for running JavaScript programs outside the browser) e can also use JavaScript in backend development!

JavaScript, an interpreted language

  • As an interpreted programming language, JS is great for interacting with a line at a time (similar to Python, but very different than Java). Where do we start?

  • The easiest way to dive in is with the Chrome browser’s Console tab in the same inspector tool we’ve used to inspect our HTML/CSS (press F12).

  • Until we learn how to interact with the HTML DOM with JS, it is recommended experimenting with the following code examples using this console to get comfortable with the basic syntax and behavior.

Console output in JavaScript

  • console.log() command is used to output values to the browser console, most often used to debug JS programs.
  • You can think of this as System.out.println in Java or print in Python.
  • Make sure you “Hide console sidebar” (1) and select “All levels” in the dropdown menu (2)
console.log("The answer is: " + 42);

Comments

// single-line comment

/**
 * multi-line
 * comment
 */
  
  • Identical to Java’s comment syntax

Comments in HTML and CSS

  • HTML: <!-- comment -->
  • CSS: /* comment */

Variables and constants

var name = expression; // define a variable globally
let name = expression; // define a variable with limited scope
const name = expression; // define a constant (cannot change)     
  • Variables are declared with the let keyword (case-sensitive).
  • Constants are declared with the const keyword
  • You may also see var used instead of let
    • this is an older convention with weaker scope - it is not recommended to use
  • Naming convention:
    • Use camelCase for variable (and function) names
    • Don’t start with a number or symbol (except _ or $)
    • Variable names are case-sensitive (i.e. age is not the same as Age)
    • Do not use JS keywords as names (e.g., let, const, function, or return)

Variables and constants

let level = 23;            // number
let accuracyRate = 0.99;   // number
let name = "ITM WebProg";  // string
let flag = true;           // boolean
let temps = [55, 60, 57.5];// array
typeof(name);              // 'string'
  • Types are not specified, but JS does have types (“loosely-typed”)
    • Primitives: number, string, boolean, array, null, undefined
    • object, function,
    • The typeof function returns a variable type

Note

Type conversion isn’t always what you expect as you will see in a moment.

A Note about declaring types in JavaScript

  • If you’ve programmed in a statically-typed language like Java, you may recall that when declaring variables, you must specify their type which stays the same during runtime.
boolean isValid = "hello!"; // error in JavaScript. boolean keyword doesn't exist
  • In a dynamically-typed language like JavaScript, you don’t need to specify the type (just use let or const) and you may change the type the variable refers to later in execution.
let isValid = true; // no error
isValid = "hello!";
isValid = 1;
isValid = true;

Number type

let enrollment = 99;
let medianGrade = 2.8;
let credits = 5 + 4 + (2 * 3);
  • Integers and real numbers are the same type (no int vs. double). All numbers in JS are floating point numbers.
  • Same operators: + - * / % ++ -- = += -= *= /= %= and similar precedence to Java.
  • Many operators auto-convert types: "2" * 3 is 6
  • NaN(“Not a Number”) is a return value from operations that have an undefined numerical result (e.g. dividing a String by a Number).

String type

let name = "Yuna Kim";                            // "Yuna Kim"
let fName = name.substring(0, name.indexOf(" ")); // "Yuna"
let len = nickName.length;                        // 8
let sport = 'Figure Skating';                     // can use "" or ''
let message = `${name}, practices ${sport}`;       // `` template literals
console.log(message) // 'Yuna Kim, practices Figure Skating'

More about strings

let count = 10;                              // 10
let stringedCount = "" + count;              // "10"
let puppyCount = count + " puppies, yay!";   // "10 puppies, yay!"
let magicNum = parseInt("42 is the answer"); // 42
let mystery = parseFloat("Am I a number?");  // NaN   
  • To convert between Numbers and Strings:
  • Escape sequences behave as in Java: \' \" \& \n \t \\
  • To access characters of a String s, use s[index] or s.charAt(index):
let firstLetter  = puppyCount[0];                            // "1"
let fourthLetter = puppyCount.charAt(3);                     // "p"
let lastLetter   = puppyCount.charAt(puppyCount.length - 1); // "!"

Common bugs when using strings

let sumNum  = 1 + 1;       // "2"
let sumStrNum  = "1" + 1;  // "11"
let sumNumStr  = 1 + "1";    // "11"
  • While Strings in JS are fairly similar to those you’d use in Java, there are a few special cases that you should be aware of.
    • Remember that length is a property (not a method, as it is in Java)
    • Concatenation with + (see the code above)

Special values: null and undefined

let foo = null;
let bar = 9;
let baz;

/* At this point in the code,
 * foo is null
 * bar is 9
 * baz is undefined
 */
  • undefined: declared but has not yet been assigned a value
  • null: exists, but was specifically assigned an empty value or null.
    • Expresses intentional a lack of identification.
  • A good motivating overview of null vs. undefined

Note

This takes some time to get used to, and remember this slide if you get confused later.

Arrays

let name = [];                          // empty array
let names = [value, value, ..., value]; // pre-filled
names[index] = value;                   // store element

let types = ["Electric", "Water", "Fire"];
let pokemon = [];       // []
pokemon[0] = "Pikachu"; // ["Pikachu"]
pokemon[1] = "Squirtle";// ["Pikachu", "Squirtle"]
pokemon[3] = "Gengar";  // ["Pikachu", "Squirtle", undefined, "Gengar"]
pokemon[3] = "Abra";    // ["Pikachu", "Squirtle", undefined, "Abra"]
  • Two ways to initialize an array
  • length property (grows as needed when elements are added)
  • You can also create an array from other data types
    • For example, when you split a string using the string.split() method

Arrays methods

array.indexOf(element, fromIndex)
array.includes(element, fromIndex)

let pokemon = ["Pikachu", "Squirtle", "Gengar", "Abra"];
let index = pokemon.indexOf("Gengar");
console.log(index); // 2

console.log(pokemon.includes("Squirtle")); // true
console.log(pokemon.includes("Jigglypuff"));  // false
  • indexOf() method is useful for finding the first index of a specific element within an array
    • If the element cannot be found, then it will return -1
  • includes() method is a simple and efficient way to check if an array contains a specific value

Conditional statements

const condition = true
const condition2 = true
if(condition) {
    console.log("The condition is true")
} else if (condition2) {
    console.log("The condition2 is true")
} else {
    console.log("The condition and condition2 are false")
}
  • Identical structure to Java’s if/else statement
  • Logical operators: > < >= <= && || !
  • Strict equality operators: === !==
  • Non-strict equality operators: == !=

More on logical operators

5 < "7"       // true
42 == 42.0    // true 
"5.0" == 5    // true  
"5.0" === 5   // false
  • Most logical operators automatically convert types
  • In the case of equality operator attempt to convert types
  • === and !== are strict equality tests; checks both type and value

Boolean type

let iLikeWebProg = true;
let myGrade = "A+" > 0; // false
if ("web programming is great") {
  console.log("true"); 
}
if (0) { /* false */ }

//converting a value into a `boolean` explicitly: 
let boolValue = Boolean(otherValue);
let boolValue = !!(otherValue);  //double not
  • Any value can be used as a boolean
    • “falsey” values: 0, 0.0, NaN, "", null, and undefined
    • “truthy” values: anything else

Repetition statements

while

let i = 1;
while (i <= 10) {
    console.log(i);
    i++;
};

for

for (let i = 0; i < 10; i++) {
    console.log(i);
}

  • The most common repetition statements in JS are the for and while statement
  • Syntax is quite similar to Java

Defining functions

// template
function name(params) {
  statement;
  return;
}

// defining a function
function greet(name) {
  console.log(`Hello ${name}`);  
}
//anonymous function
const sum = function (num1, num2) {
  return num1 + num2;
};

// calling a function
greet('WebProg');  // Hello Webprog
console.log(sum(3, 4)); // 7
  • Functions are declared using the function keyword.
  • Statements placed into functions can be evaluated in response to user events
  • An anonymous function is a function without a name that can be assigned to a variable

Arrow function expressions

() => expression

param => expression

(param) => expression

(param1, paramN) => expression

() => {
  statements
}

param => {
  statements
}

(param1, paramN) => {
  statements
}
  • Arrow function is a concise way of writing JS functions in shorter way.
  • They were introduced in the ES6 version.
  • They make our code more structured and readable (if you are familiar with the syntax)

More Array methods

const numbers = [1, 2, 3, 4, 5]
const mapTransformation = numbers.map(el => el * 10) //10,20,30,40,50
const forEachTransformation = []
numbers.forEach(el => {
    forEachTransformation.push(el * 10)
})
console.log(mapTransformation) // 10,20,30,40,50
console.log(forEachTransformation) // 10,20,30,40,50
  • The map(function) directly returns a new array with the applied transformation.
  • The forEach(function) method calls a function for each element in an array.

Using Objects

let person = {
            name: "Philip J. Fry",                           // string
            age: 23,                                         // number
            "weight": 172.5,                                 // number
            friends: ["Farnsworth", "Hermes", "Zoidberg"],   // array
            };                        

person.age;
person["weight"];   // 172.5
person.friends[2];  // "Zoidberg" 
let propertyName = "name";
console.log(person[propertyName]); //  "Philip J. Fry"
  • Objects are the most versatile structure in JS
  • You can access the fields with dot notation (.fieldName) or bracket notation ([“fieldName”]) syntax
  • You can create a new property or overwrite existing ones in an object by assigning a value

Optional chaining ?.

const user = {
  name: "John",
  address: {
    street: "Main Street",
  },
};
const otherUser = {
  name: "Jane",
};
console.log(user.address?.street); // Main Street
console.log(otherUser.address?.street); // undefined
// without optional chaining:
console.log(user.address.street); // Main Street
console.log(otherUser.address.street); // TypeError: Cannot read properties of undefined (reading 'street')
  • New operator introduced in ES2020
  • It allows you to access deeply nested properties of an object without worrying about whether the property exists or not

Next week

DOM manipulation and event-driven programming with JavaScript

Acknowledgements


Back to title slide Back to lecture slides index