JAVASCRIPT
Syntax, variables, Operators, Math, and Output
COS216
AVINASH SINGH
DEPARTMENT OF COMPUTER SCIENCE
UNIVERSITY OF PRETORIA
VIDEO
https://www.youtube.com/watch?v=FSs_JYwnAdI
WORLDWIDE INTERNET USAGE
JAVASCRIPT – INTRODUCTION
• JavaScript (JS)
• Is a dynamically typed scripting language
• Designed to add functionality to web pages
• Facilitates communication between the client and webserver
• File extension:
• .js
• Mime type:
• application/javascript
• text/javascript (obsolete)
JAVASCRIPT – HISTORY
• First release in 1995
• Created by Brendan Eich
• Originally intended Netscape Navigator 2.0
• Current developers:
• Netscape Communications Corporation
• Mozilla Foundation
• ECMA International
JAVASCRIPT – TECHNICAL DETAILS
• Standardized:
• European Computer Manufacturers Association (ECMA)
• International Organization for Standardization (ISO)
• Latest release:
• ECMAScript 14 (June, 2023)
• Other JS Implementations:
• JScript (Microsoft)
• ActionScript (Adobe)
In COS216 we use ECMAScript 5
JAVASCRIPT – NAMING
• JavaScript is not a subset/derivative of Java
• Originally named Mocha and then changed to LiveScript
• Upon receiving a trademark license by Sun Microsystems, renamed to JavaScript
• Somewhat of a marketing move of Sun to promote Java
JAVASCRIPT – DYNAMICALLY TYPED
• JavaScript is dynamically typed
• The type of variables are dynamically determined
• Syntax is similar to that of C++ and Java
• C++ and Java are statically typed
• JavaScript is not a limited language
• Due to the 'script' moniker
JAVASCRIPT – DYNAMICALLY TYPED
• JavaScript is not compiled
• The code is interpreted by the browser
• Errors are only thrown once that piece of code has been reached
• Errors and logs are show in the browser development tools
JAVASCRIPT – HTML INTEGRATION
• Integrate directly into the HTML <head>:
<html>
<head>
<script type="text/javascript">
// Place code here
</script>
</head>
<body>
</body>
</html>
JAVASCRIPT – HTML INTEGRATION
• Integrate as external script into the <head>:
<html>
<head>
<script type="text/javascript" src="myscript.js"></script>
</head>
<body>
</body>
</html>
JAVASCRIPT – HTML INTEGRATION
• Add it anywhere inside HTML
• Code can only be used after it was
defined
<html>
<body>
<!-- HTML code here -->
<script type="text/javascript">
// Place code here
</script>
<!-- HTML code here -->
</body>
</html>
JAVASCRIPT – COMMENTS
• Single-line comment:
// My single line comment here
• Multi-line comment:
/*
My
multi
line
comment
*/
JAVASCRIPT – STATEMENTS
• Statements end with a semicolon ( ; )
statement;
JAVASCRIPT – DATA TYPES
• JavaScript has the following data types:
• String
• Number
• Boolean
• Array
• Object
• Null
• Undefined
JAVASCRIPT – VARIABLES
• JavaScript is dynamically typed
var price;
var firstName;
var counter;
JAVASCRIPT – VARIABLES
• Values are assigned to variables by means of the assignment operator
price = 5.25;
firstName = "Alice";
counter = 1;
JAVASCRIPT – VARIABLES
• Can be immediately initialized
var price = 5.25;
var firstName = "Alice";
var counter = 1;
JAVASCRIPT – VARIABLES
• Variables can be reassigned
var price = 5.25;
var newPrice;
newPrice = 5.45;
price = newPrice;
price = 5.50;
JAVASCRIPT – VARIABLES
• Variables can be reassigned with different types
var price = 5.25;
var value = "Alice";
value = price;
price = false;
value = true;
JAVASCRIPT – NULL
• Can be used to clear the value of a variable
• Can be used for comparison
var beatle = "Lennon";
beatle = null;
JAVASCRIPT – UNDEFINED
• Indicates that a variable has no value
• Not the same as null
var beatle;
JAVASCRIPT – BOOLEANS
• Has a true/false value
• Can also be 0/1
• Although that would be stored as an integer
var f = false;
var t = true;
JAVASCRIPT – NUMBERS
• Can be integers or floats
var num = 9;
var dec = 5.3;
JAVASCRIPT – STRINGS
• String enclosed in quotation marks
var name = "Lennon";
• Quotation marks can be single ( ' ) or double( " )
var str1 = "I say: 'Hello'";
var str2 = 'You say: "Hello"';
JAVASCRIPT – STRINGS
• Get the length of the string
var name = "Lennon";
var size = name.length;
// size = 6
JAVASCRIPT – STRINGS
• Change to lowercase letters
var name = "Lennon";
var lower = name.toLowerCase();
// lower = "lennon"
• Change to uppercase letters
var name = "Lennon";
var upper = name.toUpperCase();
// upper = "LENNON"
JAVASCRIPT – STRINGS
• Remove white spaces from both sides
• Doesn’t change the original string
var name = " Lennon ";
var trimmed = name.trim();
// trimmed = "Lennon"
JAVASCRIPT – STRINGS
• Join two or more strings
• Can also concatenate with the + operator
var firstname = "John";
var surname = "Lennon";
firstname += " ";
var name = firstname.concat(surname);
// name = "John Lennon"
JAVASCRIPT – STRINGS
• Split a string into an array
var name = "John Winston Ono Lennon";
var names = name.split(" ");
// names = ["John", "Winston", "Ono", "Lennon"]
JAVASCRIPT – STRINGS
• Extract a substring from a string
var name = "Lennon";
var substring = name.substr(1, 3);
// substring = "enn"
JAVASCRIPT – STRINGS
• Return a character at a specific position
var name = "Lennon";
var char = name.charAt(1);
// char = "e"
• Return the position of a substring
var name = "Lennon";
var pos = name.indexOf("non");
// pos = 3
JAVASCRIPT – STRINGS
• Match a regular expression
var name = "Lennon is here";
var match = name.match(/on/g);
// match = "on"
• Search for the position of a regular expression
var name = "Lennon is here";
var match = name.search(/on/g);
// match = 4
JAVASCRIPT – CONVERSION
• We can always convert a text number to an actual number in JS
var stringNumber = “4cm";
var num = parseInt(stringNumber); // num = 4
• Similarly with floats
var stringNumber = “4,4cm";
var num = parseFloat(stringNumber); // num = 4,4
• https://www.w3schools.com/jsref/jsref_obj_global.asp
JAVASCRIPT – ARRAYS
• Data structure holding other variables
• Define a new array
var beatles = new Array();
• Or define it as an empty array
var beatles = [];
JAVASCRIPT – ARRAYS
• Adding elements by subscript
var beatles = new Array();
beatles[0] = "Lennon";
beatles[1] = "McCartney";
// beatles = ["Lennon", "McCartney"]
• Accessing elements by subscript
var lennon = beatles[0];
// lennon = "Lennon"
JAVASCRIPT – ARRAYS
• Arrays have a dynamic size
• Get the size of an array
var beatles = new Array();
var size = beatles.length;
// size = 0
JAVASCRIPT – ARRAYS
• Add elements during creation
var beatles = new Array("Lennon", "McCartney");
• Or with a different notation
var beatles = ["Harrison", "Starr"];
JAVASCRIPT – ARRAYS
• Arrays can hold different data types
var arr = ["Starr", 1, "Lennon", 2.5];
JAVASCRIPT – ARRAYS
• Add an element to the end of the array
var beatles = [];
beatles.push("Harrison");
• Add an element to the beginning of the array
var beatles = [];
beatles.unshift("Harrison");
JAVASCRIPT – ARRAYS
• Remove the first element and return it
var beatles = ["Lennon", "McCartney"];
beatles.shift();
// beatles = ["McCartney"]
• Remove the last element and return it
var beatles = ["Lennon", "McCartney"];
beatles.pop();
// beatles = ["Lennon"]
JAVASCRIPT – ARRAYS
• Concatenate two arrays
var beatles1 = ["Lennon", "McCartney"];
var beatles2 = ["Harrison", "Starr"];
var beatles = beatles1.concat(beatles2);
// beatles = ["Lennon", "McCartney", "Harrison", "Starr"]
JAVASCRIPT – ARRAYS
• Return a subset of the array
var beatles = ["Lennon", "Starr", "Harrison"];
var subBeatles = beatles.slice(2, 3);
// subBeatles = ["Harrison"]
JAVASCRIPT – ARRAYS
• Find an element in an array (from start)
var beatles = ["Lennon", "McCartney"];
var index = beatles.indexOf("Lennon");
// index = 0
• Find an element in an array (from end)
var beatles = ["Lennon", "McCartney"];
var index = beatles.lastIndexOf("Lennon");
// index = 0
JAVASCRIPT – ARRAYS
• Sort an array (ascending)
var beatles = ["Lennon", "McCartney"];
beatles.sort();
// beatles = ["Lennon", "McCartney"]
• Sort an array (descending)
var beatles = ["Lennon", "McCartney"];
beatles.sort();
beatles.reverse();
// beatles = ["McCartney", "Lennon"]
JAVASCRIPT – OBJECTS
• Enclosed in curly brackets
• Properties are defined by name-value pairs
var person = {
firstname : "John",
lastname : "Lennon",
id : 1478
};
JAVASCRIPT – OBJECTS
• Access properties
var person = {
firstname : "John",
lastname : "Lennon",
id : 1478
};
var name = person.lastname;
// name = "Lennon"
var id = person["id"];
// id = 1478
JAVASCRIPT – DECLARATION
• Variables can be declared with the new keyword
var x = new String;
var y = new Number;
var z = new Boolean;
JAVASCRIPT – OPERATORS
• Arithmetic operators
• Addition: +
• Subtraction: -
• Multiplication: *
• Division: /
• Remainder (Mod): %
JAVASCRIPT – OPERATORS
• Some can be used on all data types
var x = 1.1;
var y = (x + 4) / 3;
var name = "Lennon";
name = "John" + " " + name;
var beatle1 = ["Lennon"];
var beatle2 = ["Starr"];
var beatles = beatle1 + beatle2;
JAVASCRIPT – OPERATORS
• Can also be combined with the = operator
var x = 1.1;
x /= 3;
var name = "John";
name += " Lennon";
JAVASCRIPT – OPERATORS
• Relational operators
• Equal to: == or ===
• Not equal to: != or !==
• Smaller than: <
• Greater than: >
• Smaller than or equal: <=
• Greater than or equal: >=
JAVASCRIPT – OPERATORS
• == does type-casting
• === does not do type-casting
0 == '' // true
0 === '' // false
0 == '0' // true
0 === '0' // false
false == '0' // true
false === '0' // false
JAVASCRIPT – MATH
• Mathematical operations can be done using the Math object
• Using Pi
var pi = Math.PI;
• Using Euler’s number
var e = Math.E;
JAVASCRIPT – MATH
• Square root
var x = Math.sqrt(16);
• Power
var x = Math.pow(4, 3);
JAVASCRIPT – MATH
• Rounding to the nearest integer
var x = Math.round(1.59);
• Rounding down
var x = Math.floor(1.59);
• Rounding up
var x = Math.ceil(1.59);
JAVASCRIPT – MATH
• Get the maximum of two numbers
var x = Math.max(16, 30);
• Get the minimum of two numbers
var x = Math.min(40, -3);
• Generating a random number between 0 and 1
var x = Math.random();
JAVASCRIPT – DATE
• Handle times/dates with the Date object
var now = new Date();
• Get the current date (client side)
var date1 = new Date("April 20, 1975 11:13:00");
var date2 = new Date(1969, 8, 15);
• Create custom dates (months start at 0, not 1)
JAVASCRIPT – WRITE
• Text can be written to the console with the document object
• Displayed in the browser console under developer tools
• Write text
document.write("Hello World!");
• Write text with a newline character at the end
document.writeln("Hello World!");
JAVASCRIPT – CONSOLE
• Advanced output can be done with the console object
console.log("Hello World!");
console.debug("Debugging my site");
console.error("Something went wrong");
console.warn("Warning, warning");
console.info("This is some info");
JAVASCRIPT – POPUPS
• Show a popup message in the browser
alert("This is another popup");
• A confirmation popup with an "OK" and "Cancel" button
confirm("Do you want to leave?");
JavaScript – Popups
• Ask the user for input with an "OK" and
"Cancel" button
• Second parameter is the default value
var name = prompt("Please enter your name", "John Lennon");