0% found this document useful (0 votes)
12 views9 pages

01 - Types - Values - Variables

The document discusses the lexical structure of a programming language. It covers topics like case sensitivity, comments, literals, identifiers, reserved words, unicode, and optional semicolons. Examples are provided to illustrate each concept.

Uploaded by

Minh Quang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views9 pages

01 - Types - Values - Variables

The document discusses the lexical structure of a programming language. It covers topics like case sensitivity, comments, literals, identifiers, reserved words, unicode, and optional semicolons. Examples are provided to illustrate each concept.

Uploaded by

Minh Quang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

21/02/2024

New Programming Language

New Programming Language Lexical Structure

By: Võ Văn Hải


Email: [email protected]

1 2

1 2

Lexical Structure Lexical Structure


The Text of a JavaScript Program
▸The lexical structure of a programming language is the set
of elementary rules that specifies how you write programs ▸JavaScript is a case-sensitive language.
in that language. - This means that language keywords, variables, function names,
and other identifiers must always be typed with a consistent
- It is the lowest-level syntax of a language: it specifies what capitalization of letters.
variable names look like, the delimiter characters for comments, - The while keyword, for example, must be typed “while,” not
and how one program statement is separated from the next, … “While” or “WHILE.” Similarly, online, Online, OnLine, and
▸The lexical structure of JavaScript: ONLINE are four distinct variable names.
- Case sensitivity, spaces, and line breaks ▸JavaScript ignores spaces that appear between tokens in
- Comments programs.
- Literals - You can use spaces and newlines freely in your programs →
format and indent your programs in a neat and consistent way
- Identifiers and reserved words that makes the code easy to read and understand.
- Unicode ▸JavaScript recognizes newlines, carriage returns, and a
- Optional semicolons carriage return/line feed sequence as line terminators.
3 4

3 4

1
21/02/2024

Lexical Structure Lexical Structure


Comments Literals
▸JavaScript supports two styles of comments. ▸A literal is a data value that appears directly in a program.
- Any text between a // and the end of a line is treated as a ▸Sample literal in JavaScript
comment and is ignored by JavaScript.
- Any text between the characters /* and */ is also treated as a
comment; these comments may span multiple lines but may not
be nested.
▸Example

5 6

5 6

Lexical Structure Lexical Structure


Identifiers and Reserved Words Reserved Words
▸An identifier is simply a name. ▸In JavaScript you cannot use these reserved words as variables, labels, or
▸In JavaScript, identifiers are used to name constants, variables, properties, function names
abstract arguments await* boolean
functions, and classes and to provide labels for certain loops in JavaScript
break byte case catch
code. char class* const* continue

▸A JavaScript identifier must begin with a letter, an underscore (_), or a debugger default delete do

dollar sign ($). Subsequent characters can be letters, digits, underscores, double else enum* eval
export* extends* false final
or dollar signs.
finally float for function
▸***Digits are not allowed as the first character in JavaScript. goto if implements import*
in instanceof int interface
▸Example
let* long native new
null package private protected
public return short static
super* switch synchronized this
throw throws transient true
try typeof var void
volatile while with yield

7 8

7 8

2
21/02/2024

Lexical Structure Lexical Structure


Unicode Optional Semicolons
▸JavaScript programs are written using the Unicode ▸JavaScript uses the semicolon (;) to separate statements from one
character set, and you can use any Unicode characters in another.
- This is important for making the meaning of your code clear: without a
strings and comments. separator, the end of one statement might appear to be the beginning of the
▸For portability and ease of editing, it is common to use next, or vice versa.
- In JavaScript, you can usually omit the semicolon between two statements if
only ASCII letters and digits in identifiers. those statements are written on separate lines.
- But this is a programming convention only, and the language
allows Unicode letters, digits, and ideographs (but not emojis) in
identifiers.
- This means that programmers can use mathematical symbols
and words from non-English languages as constants and
variables.
▸Example

9 10

9 10

Types, Values, and Variables

Integrated Development Environment

11 13

11 13

3
21/02/2024

JavaScript Types JavaScript Types


Numbers
▸JavaScript types can be divided into two categories:
- Primitive types ▸JavaScript’s primary numeric type, Number, is used to represent integers
and to approximate real numbers.
• String
• Number ▸JavaScript represents numbers using the 64-bit floating-point format
• Bigint defined by the IEEE 754 standard.
- which means it can represent numbers as large as ±1.7976931348623157 × 10308 and
• Boolean as small as ±5 × 10324 .
• Undefined - It can represent all integers between −9,007,199,254,740,992 (−253) and
• Null 9,007,199,254,740,992 (253), inclusive.
• Symbol - If you use integer values larger than this, you may lose precision in the trailing digits.
• Object.
- Object types
• An object
• An array
• A date

14 15

14 15

JavaScript Types JavaScript Types


Numbers (cont.) Arithmetic in JavaScript
▸Integer Literals ▸The arithmetic operators
- In JS, a base-10 and hexadecimal (base-16) integer is used. - + for addition, - for subtraction, * for multiplication, / for division, and % for modulo,
** for exponentiation.
- The Math object can be used to explore the set of functions, operations, constants
and properties of JS supporting.
- In ECMAScript 6 and later, binary (base 2) or octal (base 8) can be used. The prefixes
0b and 0o (or 0B and 0O) is used • Source: Mozilla
▸Arithmetic in JavaScript does not raise errors in cases of overflow,
underflow, or division by zero.
- Floating-Point Literals - When the result of a numeric operation is larger than the largest representable
• Syntax: [digits][.digits][(E|e)[(+|-)]digits] number (overflow), the result is a special infinity value, Infinity.
- when the absolute value of a negative value becomes larger than the absolute value
of the largest representable negative number, the result is negative infinity, -Infinity.
▸BigInt:
- Separators in numeric literals - BigInt literals are written as a string of digits followed by a lowercase letter n.
let string = "1"+"0".repeat(100);
let bg = BigInt(string);// => 10n**100n: one googol

16 17

16 17

4
21/02/2024

JavaScript Types JavaScript Types


Dates and Times Dates and Times (cont.)
▸JavaScript defines a simple Date class for representing and manipulating ▸Timestamps
the numbers that represent dates and times. - JavaScript represents dates internally as integers that specify the number of
milliseconds since (or before) midnight on January 1, 1970, UTC time.
▸JavaScript Dates are objects, but they also have a numeric representation
- Integers as large as 8,640,000,000,000,000 are supported, so JavaScript won’t be
as a timestamp that specifies the number of elapsed milliseconds. running out of milliseconds for more than 270,000 years
- For any Date object, the getTime() method returns this internal value, and the
let timestamp = Date.now(); // The current time as a timestamp (a number). setTime() method sets it.
let now = new Date(); // The current time as a Date object. d.setTime(d.getTime() + 30000); //add 30 seconds to a Date d
let ms = now.getTime(); // Convert to a millisecond timestamp. ▸Date Arithmetic
let iso = now.toISOString(); // Convert to a string in standard format. - Date objects can be compared with JavaScript’s standard <, <=, >, and >= comparison
operators.
let century = new Date(2100, // Year 2100
0, // January - We can add/subtract one Date object from another to determine the number of
1, // 1st milliseconds between the two dates.
2, 3, 4, 5); // 02:03:04.005, local time - Example:
• Add three months and two weeks to the current date:

18 19

18 19

JavaScript Types JavaScript Types


Dates and Times (cont.) - Formatting and Parsing Date Strings Text
▸The Date class defines a number of different methods for converting Date ▸The JavaScript type for representing text is the string.
objects to strings. ▸A string is an immutable ordered sequence of 16-bit values, each of which
let d = new Date(2020, 0, 1, 17, 10, 30); // 5:10:30pm on New Year's Day 2020 typically represents a Unicode character.
d.toString() // => "Wed Jan 01 2020 17:10:30 GMT-0800 (Pacific Standard Time)" ▸String Literals: enclose the characters of the string within a matched pair
d.toUTCString() // => "Thu, 02 Jan 2020 01:10:30 GMT" of single or double quotes or backticks (' or " or `)
d.toLocaleDateString() // => "1/1/2020": 'en-US' locale - Sample

d.toLocaleTimeString() // => "5:10:30 PM": 'en-US' locale


d.toISOString() // => "2020-01-02T01:10:30.000Z"
- Strings can be written in two or more lines, as:

▸Read more at Mozilla

- Strings can be used in combination with HTML, like:

20 21

20 21

5
21/02/2024

JavaScript Types JavaScript Types


Text (cont.) - Escape Sequences Text (cont.) - Working with Strings
▸Escape Sequences in String Literals ▸Using + (concatenate) to append strings
- The backslash character (\) has a special purpose in JavaScript strings. let name = "Vo Van Hai";
let greeting = "Welcome to JavaScript," + " " + name;
Sequence Character represented
▸Strings can be compared with the standard === equality and !== inequality
\0 The NUL character (\u0000)
operators.
\b Backspace (\u0008)
- Two strings are equal if and only if they consist of exactly the same sequence of 16-bit
\t Horizontal tab (\u0009)
values.
\n Newline (\u000A)
\v Vertical tab (\u000B) ▸Strings can also be compared with the <, <=, >, and >= operators.
\f Form feed (\u000C) - String comparison is done simply by comparing the 16-bit values.
\r Carriage return (\u000D)
▸JavaScript provides a rich API for working with strings
\" Double quote (\u0022) String.prototype.anchor() String.fromCharCode() String.prototype.padStart() String.prototype.substring()
\' Apostrophe or single quote (\u0027) String.prototype.at() String.fromCodePoint() String.raw() String.prototype.sup()
String.prototype.big() String.prototype.includes() String.prototype.repeat() String.prototype.toLocaleLowerCase()
\\ Backslash (\u005C) String.prototype.blink() String.prototype.indexOf() String.prototype.replace() String.prototype.toLocaleUpperCase()
String.prototype.bold() String.prototype.isWellFormed() String.prototype.replaceAll() String.prototype.toLowerCase()
\xnn The Unicode character specified by the two hexadecimal digits nn String.prototype.charAt() String.prototype.italics() String.prototype.search() String.prototype.toString()
String.prototype.charCodeAt() String.prototype.lastIndexOf() String.prototype.slice() String.prototype.toUpperCase()
\unnnn The Unicode character specified by the four hexadecimal digits nnnn String.prototype.codePointAt() String.prototype.link() String.prototype.small() String.prototype.toWellFormed()
String.prototype.concat() String.prototype.localeCompare() String.prototype.split() String.prototype.trim()
The Unicode character specified by the codepoint n, where n is one to six hexadecimal String.prototype.endsWith() String.prototype.match() String.prototype.startsWith() String.prototype.trimEnd()
\u{n}
digits between 0 and 10FFFF (ES6) String.prototype.fixed() String.prototype.matchAll() String.prototype.strike() String.prototype.trimStart()
String.prototype.fontcolor() String.prototype.normalize() String.prototype.sub() String.prototype.valueOf()
22 23

22 23

JavaScript Types JavaScript Types


Text (cont.) - Template Literals Boolean Values
▸JS supports template literals that can include arbitrary JavaScript ▸A Boolean value represents truth or falsehood, on or off, yes or no.
expressions. ▸There are only two possible values of this type.
- The final value of a string literal in backticks is computed by evaluating any included
- The reserved words true and false evaluate to these two values.
expressions, converting the values of those expressions to strings and combining
those computed strings with the literal characters within the backticks: let a = 4, b = 3;
let name = "Vo Van Hai"; Note: template literals should be print(a===b); //false
let greeting = `Greeting, ${name}`; //Greeting, Vo Van Hai enclosed with ` (Grave Accent) symbol! print(a>b); //true
▸Pattern Matching
- JavaScript defines a datatype known as a regular expression (or RegExp) for describing
and matching patterns in strings of text. ▸Boolean values are generally the result of comparisons you make in your
- RegExps are not one of the fundamental datatypes in JavaScript, but they have a JavaScript programs.
literal syntax like numbers and strings do, so they sometimes seem like they are
fundamental. if (a >b) {
let text = "testing: 1, 2, 3"; // Sample text print(`${a} is not equal to ${b}`);
let pattern = /\d+/g; // Matches all instances of one or more digits } else {
pattern.test(text) // => true: a match exists print(`${a} and ${b} are not equal`);
text.search(pattern) // => 9: position of first match }
text.match(pattern) // => ["1", "2", "3"]: array of all matches
text.replace(pattern, "#") // => "testing: #, #, #"
text.split(/\D+/) // => ["","1","2","3"]: split on non-digits
24 25

24 25

6
21/02/2024

Type Conversions Type Conversions


JavaScript type conversions
▸JavaScript variables can be converted to a new variable and another data No. Original Value Converted to Converted to String Converted to
type: Number Boolean
- Automatically (by JavaScript itself - implicit). 1 false 0 "false" false
- Use of a JavaScript function (casting - explicit). 2 true 1 "true" true
▸Implicit Conversions 3 0 0 "0" false
10 + " objects" // => "10 objects": Number 10 converts to a string 4 1 1 "1" true
"7" * "4" // => 28: both strings convert to numbers 5 "0" 0 "0" true
let n = 1 - "x"; // n == NaN; string "x" can't convert to a number 6 "000" 0 "000" true
n + " objects" // => "NaN objects": NaN converts to string "NaN" 7 "1" 1 "1" true
8 NaN NaN "NaN" false
▸Explicit Conversions
9 Infinity Infinity "Infinity" true
Number("3") // => 3 10 -Infinity -Infinity "-Infinity" true
String(false) // => "false": Or use false.toString() 11 "" 0 "" false
Boolean([]) // => true 12 "20" 20 "20" true
26 27

26 27

Type Conversions Variables


JavaScript type conversions Declaration
No. Original Value Converted to Number Converted to Converted to ▸Variables are Containers for Storing Data
String Boolean ▸JavaScript Variables can be declared in 4 ways: It is considered good
13 "20" 20 "20" true - Automatically programming
- Using var keyword practice to always
14 "twenty" NaN "twenty" true - Using let keyword declare variables
15 [] 0 "" true - Using const keyword before use.

16 [20] 20 "20" true ▸Note


17 [10,20] NaN "10,20" true - The var keyword was used in all JavaScript code from 1995 to 2015.
- The let and const keywords were added to JavaScript in 2015.
18 ["twenty"] NaN "twenty" true
- The var keyword should only be used in code written for older browsers.
19 ["ten","twenty"] NaN "ten,twenty" true
▸When to use var, let, or const?
20 function(){} NaN "function(){}" true 1. Always declare variables.
21 {} NaN "[object Object]" true 2. Always use const if the value should not be changed.
3. Always use const if the type should not be changed (Arrays and Objects).
22 null 0 "null" false 4. Only use let if you can't use const .
5. Only use var if you MUST support old browsers.
23 undefined NaN "undefined" false

28 29

28 29

7
21/02/2024

Variables Variables
Declarations with let and const Variable Declarations with var
▸Variables declaration and assignment values ▸In versions of JavaScript before ES6, the only way to declare a variable is
let i; // Value = undefined let message = "hello"; with the var keyword, and there is no way to declare constants.
let sum; let i = 0, j = 0, k = 0; - The syntax of var is just like the syntax of let
let i, sum; let x = 2, y = x*x; // Initializers can use previously declared variables
var x;
var data = [], count = data.length;
▸It is a good programming practice to assign an initial value to your
variables when you declare them.
▸To declare a constant instead of a variable, use const instead of let ▸it is legal to declare the same variable multiple times with var.

const H0 = 74; // Hubble constant (km/s/Mpc) //If you re-declare a JavaScript variable declared with var, it will not lose its value.
const C = 299792.458; // Speed of light in a vacuum (km/s) var carName = "Volvo";
const AU = 1.496E8; // Astronomical Unit: distance to the sun (km) var carName; //let will cause with error
print(carName) //==>Volvo

30 31

30 31

Variables Summary
Destructuring Assignment
▸How to write and manipulate numbers and strings of text in JavaScript.
▸In a destructuring assignment, the value on the righthand side of the
equals sign is an array or object (a “structured” value), and the lefthand ▸How to work with JavaScript’s other primitive types: booleans, Symbols,
side specifies one or more variable names using a syntax that mimics array
and object literal syntax. null, and undefined.

let [x, y] = [1, 2]; // Same as let x=1, y=2 let [x, y] = [1]; // x == 1; y == undefined ▸The differences between immutable primitive types and mutable
[x, y] = [x + 1, y + 1]; // Same as x = x + 1, y = y + 1 [x, y] = [1, 2, 3]; // x == 1; y == 2
reference types.
[x, y] = [y, x]; // Swap the value of the two variables [, x, , y] = [1, 2, 3, 4]; // x == 2; y == 4
[x, y] // => [3,2]: the incremented and swapped values let [x, ...y] = [1, 2, 3, 4]; // x=1, y == [2,3,4]
▸How JavaScript converts values implicitly from one type to another and
▸Destructuring assignment works with functions that return arrays of values how you can do so explicitly in your programs.
let foo = () => {
return [1, 2];
▸How to declare and initialize constants and variables (including with
}
destructuring assignment) and the lexical scope of the variables and
Read more at MDN web docs
let [x, y] = foo(); constants you declare.
print(x + ", " + y); //1, 2

32 33

32 33

8
21/02/2024

Exercise
1. https://www.geeksforgeeks.org/practice-javascript-online/
2. https://www.w3schools.com/js/exercise_js.asp
3. …

34 35

34 35

You might also like