using let rather than var

Using let rather than var and use strict can avoid some overwriting of variables i will write a function here that shows how let throws an error. This function now gives an error in the console. Uncaught SyntaxError: Identifier 'x' has already been declared

both of these examples crash as the 1st one detects an error, but you can still see how let can be used to avoid code errors. 

Demo

CSS

* {
  box-sizing: border-box;
  transition: all 0.2s;
  scroll-behavior: smooth;
}

JS

function run_function() {
  "use strict";
  let x = "This is X";
  let x = "This is not X?";
  write_result(x);
  return x;
}

function run_function_vars() {
  var x = "This is X";
  var x = "This is not X?";
  write_result(x);
  return x;
}

// this is a common function just to write the content into the result div
function write_result(result) {
  var result_html = document.getElementById("result");
  result_html.innerHTML = result;
}

HTML

<div id='result' class='mb-3 alert alert-primary'>..</div>
<button onclick='run_function();' class='btn btn-primary mb-1'>Run Function using let</button>
<button onclick='run_function_vars();' class='btn btn-primary mb-1'>Run Function using var</button>

Working Result

..

Other Items in javascript
Page Views

This page has been viewed 121 times.

Search Code
Search Code by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code snippits here, mostly for my reference. Also if i find a good site, i usually add it here.

❤👩‍💻🕹