DEV Community

Michael Flores
Michael Flores

Posted on • Updated on

JavaScript Basics

We use JS to program the behavior of web pages. It can change..

  • HTML Content
  • HTML Attributes
  • HTML Styles

We can also use it to hide and show elements on a page. The code must go either in a .js file or in script tags.

<body>
<p id="message">Default Message</p>
<button onclick="change()">Change Message</button>
//or <script src="external.js">
<script>

function changeMessage() {
  document.getElementById("message").innerHTML = "Hello World";
}

<script>
</body>
Enter fullscreen mode Exit fullscreen mode

Normally we place the script tag in the bottom of the body to improve display speed. It is better to use an external JS file to separate code for easier read. You can also display data with

window.alert(5 + 6)
document.write() //dont use this, it will delete all HTML
console.log() //debugging
Enter fullscreen mode Exit fullscreen mode

A JS statement has values, operators, keywords, expressions, or comments. Keywords include for, if, else, function, let, switch, etc. An expression is what eventually computes to a value.

Variables

Variable identifiers can start with letters, _, or $, but no numbers. Adding a number and a string the result will always be a string.

let _price = 45;
let myName; //value is undefined
const theStr = "myString";

let fullName = "john" + "doe"; //johndoe

const combine = "5" + 2 + 3; //523 as a string

const 2 + 4 + "8" + 2 + 3; //6823 as a string
Enter fullscreen mode Exit fullscreen mode

Operators

let sum = 0;
let value = 5;
sum += value; // sum = sum + value
Enter fullscreen mode Exit fullscreen mode

=== means equal value AND type
!== means not equal value AND type
? : ternary

Top comments (0)