Skip to content

[Notes] JavaScript

May 30, 2022

Introduction

JavaScript is a scripting language, weakly typed, no compilation needed, runs in browsers. Completely unrelated to Java.

Components:

ComponentPurpose
ECMA ScriptCore JS syntax foundation
BOMBrowser Object Model, browser operations
DOMDocument Object Model, page element manipulation

Writing Locations

Data Types

number, string, boolean, object, undefined

var a = 1; var b = "hello"; var c = true;
typeof a; // returns the type

Operators

Arithmetic: + - * / % ++ -- Relational: > >= < <= != == === Logical: && || ! Ternary: condition ? expr1 : expr2

Control Flow

if (score >= 90) { alert("Excellent"); }
else if (score >= 80) { alert("Good"); }
else { alert("Fail"); }

switch(parseInt(score/10)) {
  case 10: case 9: alert("Excellent"); break;
  case 8: alert("Good"); break;
  default: alert("Fail");
}

while(condition){ body; }
do { body; } while(condition);
for(var i=0; i<10; i++){ body; }

Functions

function name(params) { body; return value; }
var fn = function(params) { body; }; // anonymous function

Image Carousel

<img id="img" src="images/01.jpg">
<script>
var img = document.getElementById("img");
var count = 1;
function changeImageSrc() {
  count++;
  img.src = "images/0" + count + ".jpg";
  if (count == 8) count = 0;
}
window.setInterval(changeImageSrc, 2000);
</script>

JS Events

Format: element.event = handler

EventDescription
onloadPage/image loaded
onclickMouse click
onsubmitForm submit
onblur/onfocusElement focus change
onkeydown/upKeyboard press/release
onmouseover/outMouse enter/leave
onchangeContent changed
Previous
[Notes] Configuring DNS Services on CentOS 7
Next
[Notes] SQL Injection