Introduction to Javascript & Typescript Rony Setyawan,S.T.,M.Kom.
What is JavaScript ? JavaScript is a programming language. It is lightweight and most commonly used as a part of web pages. It is an interpreted programming language with object-oriented capabilities. JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the JavaScript engine.
Javascript is single-threaded, non-blocking, asynchronous, concurrent language. ● Single-threaded means that it runs only one thing at a time. ● Non-blocking & Asynchronous means that it doesn't wait for the response of an API call, I/O events, etc., and can continue the code execution. ● Concurrent means executing multiple tasks at the same time but not simultaneously. E.g. two tasks works in overlapping time periods. For more information, watch this video What is JavaScript ?
● Easy to Learn ● Popularity ● Large Community ● Speed ● Versatility ● Interoperability Why Use JavaScript ?
Javascript Code Structure Single Statement ; is Semicolon
Variable Variable is a “named storage” for data. We can use variable to store any data you need.
In package delivery apps, there’s information about package details, address, sender’s name, etc. Variable are used to store all the information. Example
Code Example Create (declare) variable String “Hello” Store data using assignment operator “=”
Different ways to declare variable : ● var : To create global variables ● let : To create scoped, replaceable variables ● const : Can’t be updated or redeclared within the scope Variable Declaration
Variable Naming ● Must contain only letters, digits, or the symbols “$” and “_” ● The first character must not digit ● Case-sensitive ● Can’t use reserved words
A value in JavaScript is always of a certain type. Primitive data types : The predefined data types provided by JavaScript. Non-primitive data types : The data types that are derived from primitive data types. Primitive String Used to represent textual data Number & BigInt Used to hold decimal values as well as values without decimals Boolean Represents a logical entity and can have two values: true and false Null Has exactly one value: null. Represents the intentional absence of any object value Undefined A variable that has not been assigned a value has the value undefined Data Types Non Primitive Object Is an entity having properties and methods (keyed collection) → Will be explained in the next session Array Used to store more than one element under a single variable → Will be explained in the next session
Data Types
Mutable vs Immutable ● Mutable is a type of variable that can be changed. (contains of: non primitive) it is also called as reference type ● Immutable are the objects whose state cannot be changed once the objects is created. (contains of: primitive) immutable it is also called as value type. ● Declaring variable with const doesn’t make the value immutable. It depends on data type.
Mutable vs Immutable Value types are been stored on the Stack in our memory. When storing a value type in memory, it adds an element to the top of the stack with the value of the newly created variable. When creating a new variable and assigned the first one to the new one, it adds a new element on top of the stack with the value of the new variable. “Jhonny” The Stack “Jhonny” 1 2 The first variable — name gets into the stack with the value of the variable data. Then, the newName gets into the stack in a new memory location with the value of the variable data.
Mutable vs Immutable Reference types are been stored on the Heap. The Heap, indifference from the stack, has no order of how to store the data. When storing a reference type in memory, it adds a new element to the top of the stack, when its value is a pointer/reference to the address of the object that has been stored on the heap. “Jhonny” The Stack “Jhonny” 1 2 PersonPointer 3 newPerson Pointer 4 The Heap { name: ‘Jhonny’, age: 26 }
Mutable vs Immutable Immutable Tr y t o c h a n g e v a l u e i n newName variable, check out the result! Does that change name variable value? “Jhonny” The Stack “Jhonny” 1 2 PersonPointer 3 newPerson Pointer 4 The Heap { name: ‘Jhonny’, age: 26 }
Mutable vs Immutable Mutable T r y t o c h a n g e v a l u e i n newPerson variable, check out the result! Does that change Person variable value? “Jhonny” The Stack “Jhonny” 1 2 PersonPointer 3 newPerson Pointer 4 The Heap { name: ‘Jhonny’, age: 26 }
With that in mind, we can say that a value type is immutable where a reference type is mutable. Mutable vs Immutable “Jhonny” The Stack “Jhonny” 1 2 PersonPointer 3 newPerson Pointer 4 The Heap { name: ‘Jhonny’, age: 26 }
● padStart ● padEnd ● chartAt ● charCodeAt ● split ● indexOf ● lastIndexOf ● search String Built-in Method ● slice ● substring ● substr ● replace ● toUpperCase ● toLowerCase ● concat ● trim https://developer.mozilla.org/en-US/docs/Web/JavaScript/ Reference/Global_Objects/String
Template Literals ● Template literals (template strings) allow you to use strings or embedded expressions in the form of a string. ● Template literals are enclosed by backtick (`) characters instead of double or single quotes. ● With template literals, you can get : ○ A multiline string → a string that can span multiple lines. ○ String formatting → the ability to substitute part of the string for the values of variables or expressions. This feature is also called string interpolation. ○ HTML escaping → the ability to transform a string so that it’s safe to include in HTML.
Global built-in method & property ● Number ● parseInt ● parseFloat ● MAX_VALUE ● MIN_VALUE ● POSITIVE_INFINITY ● NEGATIVE_INFINITY ● NaN Number Built-in Method Number built-in method ● toString ● toExponential ● toFixed ● toPrecision ● valueOf
Type Conversion ● String Conversion ○ String(123) // return a string from a number literal 123 ● Numeric Conversion ○ const num = "3" * "3" // return 9 in number ○ Number("3.14") // return 3.14 in number ● Boolean Conversion ○ Boolean(1) // return true ○ Boolean(0) // return false ○ Boolean("Hello") // return true ○ Boolean("") // return false
Date Data Type It stores the date, time and provides methods for date/time management.
Set Methods ● setDate ● setFullYear ● setHours ● setMilliseconds ● setMinutes ● setMonth ● setSeconds ● setTime Date Built-in Method Get Methods ● getFullYear ● getMonth ● getDate ● getHours ● getMinutes ● getSeconds ● getMilliseconds ● getTime ● getDay ● Date.now ● Date.parse
Basic Operators Operator Description + Addition - Subtraction * Multiplication / Division % Remainder (modulo) ** Exponentiation
● An operand is what operators are applied to. For instance, in the multiplication of 5 * 2 there are two operands: the left operand is 5 and the right operand is 2. Sometimes, people call these “arguments” instead of “operands”. Unary,Binary and Operand ● An operator is unary if it has a single operand. For example, the unary negation - reverses the sign of a number. ● An operator is binary if it has two operands. The same minus exists in binary form as well.
Note : Only work with binary “+”. Other arithmetic operators work only with numbers and always convert their operands to numbers. String Concatenation with binary“+”
Modify in Place We often need to apply an operator to a variable and store the new result in that same variable.
Increment & Decrement ● Increasing or decreasing a number by one is among the most common numerical operations. ● Increment ++ increases a variable by 1. ● Decrement -- decreases a variable by 1
Postfix & Prefix Form ● The operators ++ and -- can be placed either before or after a variable. ● When the operator goes after the variable, it is in “postfix form”: counter++. ● The “prefix form” is when the operator goes before the variable: ++counter. ● If we’d like to increase a value and immediately use the result of the operator, we need the prefix form ● If we’d like to increment a value but use its previous value, we need the postfix form
Comparison Operators Comparison operators are used in logical statements to determine equality or difference between variables or values. Given that x = 5, this table would explains the comparison operators
What is TypeScript? TypeScript is a superset of JavaScript, which means that it adds additional features to JavaScript, but does not break any existing JavaScript code. The main feature that TypeScript adds is static typing, which allows developers to specify the types of data that variables and functions can hold. This can help to catch errors early in the development process and make code more maintainable.
Why use TypeScript? There are several benefits to using TypeScript, including: ● Improved type safety: TypeScript's static type checking can help to catch errors early in the development process, which can save time and frustration. ● Better code readability: TypeScript's type annotations can make code more readable and easier to understand. ● Increased developer productivity: TypeScript can help developers to be more productive by catching errors early and making code more maintainable.
To get started with TypeScript, you can follow these steps: ● Install TypeScript: You can install TypeScript using npm or yarn. ● Create a TypeScript file: Create a file with a .ts extension. ● Write TypeScript code: You can write TypeScript code using the same syntax as JavaScript. ● Compile TypeScript code: You can compile TypeScript code into JavaScript code using the TypeScript compiler. ● Reference : https://www.typescriptlang.org/docs/handbook/typescript-tooling- in-5-minutes.html Getting started with TypeScript
Example
Resources TypeScript-documentation: https://www.typescriptlang.org/docs TypeScript-Handbook: https://www.typescriptlang.org/docs/handbook/intro.html TypeScript-tutorials: https://www.freecodecamp.org/news/learn-typescript- beginners-guide
Exercises Task Expectation Write a code to find area of rectangle Input: length = 5, width = 3 Output: 15 Write a code to find diameter, circumference and area of a circle Input: radius = 5 Output : diameter = 10, circumference = 31.4159, area = 78.539 Write a code to find angles of triangle if two angles are given Input: a = 80, b = 65 Output: 35 Write a code to get difference between dates in days. Input: date1 = 2024-03-19, date2 = 2024-03-21 Output: 2 Write a code to print your name initial in uppercase Input: John Doe Output: JD

Introduction to Javascript and Typescript.pdf

  • 1.
    Introduction to Javascript &Typescript Rony Setyawan,S.T.,M.Kom.
  • 2.
    What is JavaScript? JavaScript is a programming language. It is lightweight and most commonly used as a part of web pages. It is an interpreted programming language with object-oriented capabilities. JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the JavaScript engine.
  • 3.
    Javascript is single-threaded,non-blocking, asynchronous, concurrent language. ● Single-threaded means that it runs only one thing at a time. ● Non-blocking & Asynchronous means that it doesn't wait for the response of an API call, I/O events, etc., and can continue the code execution. ● Concurrent means executing multiple tasks at the same time but not simultaneously. E.g. two tasks works in overlapping time periods. For more information, watch this video What is JavaScript ?
  • 4.
    ● Easy toLearn ● Popularity ● Large Community ● Speed ● Versatility ● Interoperability Why Use JavaScript ?
  • 5.
    Javascript Code Structure SingleStatement ; is Semicolon
  • 6.
    Variable Variable is a“named storage” for data. We can use variable to store any data you need.
  • 7.
    In package deliveryapps, there’s information about package details, address, sender’s name, etc. Variable are used to store all the information. Example
  • 8.
    Code Example Create (declare)variable String “Hello” Store data using assignment operator “=”
  • 9.
    Different ways todeclare variable : ● var : To create global variables ● let : To create scoped, replaceable variables ● const : Can’t be updated or redeclared within the scope Variable Declaration
  • 10.
    Variable Naming ● Mustcontain only letters, digits, or the symbols “$” and “_” ● The first character must not digit ● Case-sensitive ● Can’t use reserved words
  • 11.
    A value inJavaScript is always of a certain type. Primitive data types : The predefined data types provided by JavaScript. Non-primitive data types : The data types that are derived from primitive data types. Primitive String Used to represent textual data Number & BigInt Used to hold decimal values as well as values without decimals Boolean Represents a logical entity and can have two values: true and false Null Has exactly one value: null. Represents the intentional absence of any object value Undefined A variable that has not been assigned a value has the value undefined Data Types Non Primitive Object Is an entity having properties and methods (keyed collection) → Will be explained in the next session Array Used to store more than one element under a single variable → Will be explained in the next session
  • 12.
  • 13.
    Mutable vs Immutable ●Mutable is a type of variable that can be changed. (contains of: non primitive) it is also called as reference type ● Immutable are the objects whose state cannot be changed once the objects is created. (contains of: primitive) immutable it is also called as value type. ● Declaring variable with const doesn’t make the value immutable. It depends on data type.
  • 14.
    Mutable vs Immutable Valuetypes are been stored on the Stack in our memory. When storing a value type in memory, it adds an element to the top of the stack with the value of the newly created variable. When creating a new variable and assigned the first one to the new one, it adds a new element on top of the stack with the value of the new variable. “Jhonny” The Stack “Jhonny” 1 2 The first variable — name gets into the stack with the value of the variable data. Then, the newName gets into the stack in a new memory location with the value of the variable data.
  • 15.
    Mutable vs Immutable Referencetypes are been stored on the Heap. The Heap, indifference from the stack, has no order of how to store the data. When storing a reference type in memory, it adds a new element to the top of the stack, when its value is a pointer/reference to the address of the object that has been stored on the heap. “Jhonny” The Stack “Jhonny” 1 2 PersonPointer 3 newPerson Pointer 4 The Heap { name: ‘Jhonny’, age: 26 }
  • 16.
    Mutable vs Immutable Immutable Try t o c h a n g e v a l u e i n newName variable, check out the result! Does that change name variable value? “Jhonny” The Stack “Jhonny” 1 2 PersonPointer 3 newPerson Pointer 4 The Heap { name: ‘Jhonny’, age: 26 }
  • 17.
    Mutable vs Immutable Mutable Tr y t o c h a n g e v a l u e i n newPerson variable, check out the result! Does that change Person variable value? “Jhonny” The Stack “Jhonny” 1 2 PersonPointer 3 newPerson Pointer 4 The Heap { name: ‘Jhonny’, age: 26 }
  • 18.
    With that inmind, we can say that a value type is immutable where a reference type is mutable. Mutable vs Immutable “Jhonny” The Stack “Jhonny” 1 2 PersonPointer 3 newPerson Pointer 4 The Heap { name: ‘Jhonny’, age: 26 }
  • 19.
    ● padStart ● padEnd ●chartAt ● charCodeAt ● split ● indexOf ● lastIndexOf ● search String Built-in Method ● slice ● substring ● substr ● replace ● toUpperCase ● toLowerCase ● concat ● trim https://developer.mozilla.org/en-US/docs/Web/JavaScript/ Reference/Global_Objects/String
  • 20.
    Template Literals ● Templateliterals (template strings) allow you to use strings or embedded expressions in the form of a string. ● Template literals are enclosed by backtick (`) characters instead of double or single quotes. ● With template literals, you can get : ○ A multiline string → a string that can span multiple lines. ○ String formatting → the ability to substitute part of the string for the values of variables or expressions. This feature is also called string interpolation. ○ HTML escaping → the ability to transform a string so that it’s safe to include in HTML.
  • 21.
    Global built-in method& property ● Number ● parseInt ● parseFloat ● MAX_VALUE ● MIN_VALUE ● POSITIVE_INFINITY ● NEGATIVE_INFINITY ● NaN Number Built-in Method Number built-in method ● toString ● toExponential ● toFixed ● toPrecision ● valueOf
  • 22.
    Type Conversion ● StringConversion ○ String(123) // return a string from a number literal 123 ● Numeric Conversion ○ const num = "3" * "3" // return 9 in number ○ Number("3.14") // return 3.14 in number ● Boolean Conversion ○ Boolean(1) // return true ○ Boolean(0) // return false ○ Boolean("Hello") // return true ○ Boolean("") // return false
  • 23.
    Date Data Type Itstores the date, time and provides methods for date/time management.
  • 24.
    Set Methods ● setDate ●setFullYear ● setHours ● setMilliseconds ● setMinutes ● setMonth ● setSeconds ● setTime Date Built-in Method Get Methods ● getFullYear ● getMonth ● getDate ● getHours ● getMinutes ● getSeconds ● getMilliseconds ● getTime ● getDay ● Date.now ● Date.parse
  • 25.
    Basic Operators Operator Description +Addition - Subtraction * Multiplication / Division % Remainder (modulo) ** Exponentiation
  • 26.
    ● An operandis what operators are applied to. For instance, in the multiplication of 5 * 2 there are two operands: the left operand is 5 and the right operand is 2. Sometimes, people call these “arguments” instead of “operands”. Unary,Binary and Operand ● An operator is unary if it has a single operand. For example, the unary negation - reverses the sign of a number. ● An operator is binary if it has two operands. The same minus exists in binary form as well.
  • 27.
    Note : Onlywork with binary “+”. Other arithmetic operators work only with numbers and always convert their operands to numbers. String Concatenation with binary“+”
  • 28.
    Modify in Place Weoften need to apply an operator to a variable and store the new result in that same variable.
  • 29.
    Increment & Decrement ●Increasing or decreasing a number by one is among the most common numerical operations. ● Increment ++ increases a variable by 1. ● Decrement -- decreases a variable by 1
  • 30.
    Postfix & PrefixForm ● The operators ++ and -- can be placed either before or after a variable. ● When the operator goes after the variable, it is in “postfix form”: counter++. ● The “prefix form” is when the operator goes before the variable: ++counter. ● If we’d like to increase a value and immediately use the result of the operator, we need the prefix form ● If we’d like to increment a value but use its previous value, we need the postfix form
  • 31.
    Comparison Operators Comparison operators areused in logical statements to determine equality or difference between variables or values. Given that x = 5, this table would explains the comparison operators
  • 32.
    What is TypeScript? TypeScriptis a superset of JavaScript, which means that it adds additional features to JavaScript, but does not break any existing JavaScript code. The main feature that TypeScript adds is static typing, which allows developers to specify the types of data that variables and functions can hold. This can help to catch errors early in the development process and make code more maintainable.
  • 33.
    Why use TypeScript? Thereare several benefits to using TypeScript, including: ● Improved type safety: TypeScript's static type checking can help to catch errors early in the development process, which can save time and frustration. ● Better code readability: TypeScript's type annotations can make code more readable and easier to understand. ● Increased developer productivity: TypeScript can help developers to be more productive by catching errors early and making code more maintainable.
  • 34.
    To get startedwith TypeScript, you can follow these steps: ● Install TypeScript: You can install TypeScript using npm or yarn. ● Create a TypeScript file: Create a file with a .ts extension. ● Write TypeScript code: You can write TypeScript code using the same syntax as JavaScript. ● Compile TypeScript code: You can compile TypeScript code into JavaScript code using the TypeScript compiler. ● Reference : https://www.typescriptlang.org/docs/handbook/typescript-tooling- in-5-minutes.html Getting started with TypeScript
  • 35.
  • 36.
  • 37.
    Exercises Task Expectation Write acode to find area of rectangle Input: length = 5, width = 3 Output: 15 Write a code to find diameter, circumference and area of a circle Input: radius = 5 Output : diameter = 10, circumference = 31.4159, area = 78.539 Write a code to find angles of triangle if two angles are given Input: a = 80, b = 65 Output: 35 Write a code to get difference between dates in days. Input: date1 = 2024-03-19, date2 = 2024-03-21 Output: 2 Write a code to print your name initial in uppercase Input: John Doe Output: JD