Grammar: Simple JavaScript Code

Topics

Javascript 
   functions

   variables
       types can be: string number boolean 
       type is determined by context
   
   strings
   
   numbers
      input
      aritmetic operators, PEMDAS
      
   boolean
      true false
      used in conditions (x > y)
      
   output
                

// FILE: grammar.js
// wyatt


// ask name and greet the user 
function promptAndGreet()
{
  // declare two variables and prompt the user for input
  var fName = prompt('What is your first name?', ''); // prompt and default value
  var lName = prompt('What is your last name?', ''); 
  
  // create output by generating HTML with variable values embedded
  document.write('

Welcome ' + fName + " " + lName + '

'); // join strings with "+" // use built-in js functionality to manipulate string document.write('

Your last name in uppercase is ' + lName.toUpperCase() + '

'); document.write('

Your last name in lowercase is ' + lName.toLowerCase() + '

'); } // get numbers from user // use variables to compute and report function messWithNumbers() { // get values var num1 = Number(prompt("Enter a number",0)); var num2 = Number(prompt("Enter a number",0)); /* NOTE: If you do this to read in numbers: var num1 = prompt("Enter a number",0); var num2 = prompt("Enter a number",0); And read in 7 and 4 as the input, you get: "The sum of 7 + 4 is 74" WHY?? */ // start html output setup document.write("

"); // note inline css // do the math and display the results var num3 = num1 + num2; document.write("The sum of " + num1 + " + " + num2 + " is " + num3); num3 = num1 - num2; document.write("
The result of " + num1 + " - " + num2 + " is " + num3); num3 = num1 * num2; document.write("
The product of " + num1 + " * " + num2 + " is " + num3); num3 = num1 / num2; document.write("
The result of " + num1 + " / " + num2 + " is " + num3); num3 = num1 % num2; document.write("
The result of " + num1 + " % " + num2 + " is " + num3); // finish up the html document.write("

"); }

/*
FILE: grammar.css
wyatt
*/
   /* css rule */
   body /* tag selector */
   {
     background-color:white; /* property:value */
   }
   .sample /* class selector */
   {
     background-color:#ddd;  /* property:value */
     color:red;   /* property:value */
     padding:20px;
   }

<!DOCTYPE html>
<!-- FILE: grammar.html -->
<!-- wyatt -->
<html>
<head> 
    <title>grammar: how to write js code</title>
    <meta charset="UTF-8" />
    <script src="grammar.js"></script>            
    <link rel="stylesheet" href="grammar.css" />  
</head>
<body>
   

JS Grammar

The horizontal rule below ends the html in this file. Everything below that line is created "on the fly" by javascript...


</body> </html>