Just want to print out cheese to the Dom or somewhere, someone know ?
<html>
<script>
function somethingInLookup(val) {
var result="";
var lookup = {
alpha: "Airbus",
beta: "Bus",
"charlie": "Cheese",
}; }
// oh just realised i need to do this.
let result = somethingInLookup("charlie");
document.write(result);
// let result = lookup[charlie];
// document.write(result);
</script>
</html>
Hi, you didn’t really find the a key in the somethingInLookup function.
Maybe you could tweak your code a bit, like so:
function somethingInLookup(val) {
var result = "";
var lookup = {
alpha: "Airbus",
beta: "Bus",
charlie: "Cheese"
};
if (val in lookup) {
// if property is in lookup
return lookup[val]; // return the value of the key
}
return; // else quit running the function
}
// oh just realised i need to do this.
let result = somethingInLookup("alpha");
console.log(result);
document.write(result);
// let result = lookup[charlie];
// document.write(result);
Not really. The function quits running when it hits a return statement. In case you have more codes that it conditional and the condition is not met, you can just return in the if block. Assume this is in a function:
...
if (!condition) { // say condition not met
return; // the function stops executing here
}
// removes the need for an else block
// else do something
console.log(5) // here will not be reached if condition is not met
return 6; // not reached