Javascript: why to declare the same value of the same variable twice? - javascript

I want a prompt appear and ask user to type in a correct password. And every time user types in the wrong pw, the prompt should re-appear. I don't understand why the following code wouldn't work:
var secret = prompt("What is the password?");
while ( secret !== "sesame" ) {
secret;
}
document.write("Welcome.");
If "secret" is a global variable then inside the while loop it should be interpreted as having the value of prompt("What is the password?")?
But it turns out that I should write secret = prompt("What is the password?");inside the while loop:
var secret = prompt("What is the password?");
while ( secret !== "sesame" ) {
secret = prompt("What is the password?");
}
document.write("Welcome.");
Why to declare the same value of variable secret twice?

A line of code that is simply secret; does nothing - it merely references, but does nothing with, a variable named secret.
What you mean to do is:
var secret;
while(secret !== 'secretpassword') secret = prompt("What's the password?");
For the first iteration of the loop secret does not equal the secret password, so the prompt is run. And it will run repeatedly until the correct one is entered.
However, there's a lot of problems with your approach.
Firstly, ever-lasting dialog windows (of which a prompt is a kind) are not very UI friendly; they necessarily demand focus so you can't click away from them without interacting with them. What if the user wanted to dismiss the prompt and click a "forgot pass" link or use some other part of the page?
Secondly, storing a password in JavaScript is a massive and obvious security risk, but I'll assume this is a tutorial or homework of some kind where the focus is not on security.
Thirdly, document.write() is long-ago deprecated and there's almost no use for it these days. Look instead into DOM-scripting.

When you assign an expression in a variable, the variable only contains the value returned by that expression, not the expression itself
Therefore, evaluating the variable won't have any effect, and won't evaluate the assigned expression again.
If you don't want to repeat the function call, you can use a do while loop
var secret;
do {
secret = prompt("What is the password?");
} while ( secret !== "sesame" );
But of course, JS passwords are useless

Related

Using regex to test out of 4 words in an array has a perfect match

I was tasked with a project of creating a CV site were the user uploads a .docx file and the details is extracted from the file and is automatically inputted in the template designed by me,
I have been able to extract the details .docx file with JavaScript and the extracted details was kept in an array to make it easy to identify words with indexing. For example
[Adeola Emmanuel, adeolaemmanuel#gmail.com, pharmacist, 2 ketu ikorodu lagos, etc].
where i need help is not all CV uploaded by the user has the name coming first or email coming second but its sure that they come within 0,6 of the array so i decided to write a function that will help with that but its not working
var email = email(text.slice(0, 5));
function email(email) {
var re = /.{1,}#[^.]{1,}/ig;
if (!re.test(email)) {
email = text.slice(0, 1);
return email;
} else if (re.test(email)) {
email = text.slice(3, 5);
return email;
}
}
You can use the find array method:
function getEmail(arr) {
let re = /\S#[^.\s]/;
return arr.find(str => re.test(str));
}
let text = ["Adeola Emmanuel", "adeolaemmanuel#gmail.com", "pharmacist", "2 ketu ikorodu lagos"];
let email = getEmail(text.slice(0, 5));
console.log(email);
Some remarks:
{1,} in regular expressions can be shortened to just +
You actually don't need to test for multiple occurrences with +, since you would already accept one occurrence. So that also means you would be OK with just one non-point character after the #.
Neither of the regex suffixes (ig) have any use in your regex.
The .test method should get a string as argument, not an array. So you need to pass it email[0] for example.
For a full test of whether some string is a valid email address, the regular expression would be way more complex
When an if condition is false, there is no need to test the exact opposite in the else block: by exclusion that opposite condition will always be true when it gets executed.
The slice of an array is still an array, so returning text.slice(3, 5); in the else block does not make sense. You want to return a string.
You need a loop to inspect other array elements for as long as you don't have a match and have not reached the end of the array. So some loop construct is needed. You can use for, while, or any of the array methods that do such looping. find is particular useful in this case.
Don't give your function the same name as another variable (email) as only one value can be assigned to that variable (a function, a string, or still something else). So in your case you'll lose the function definition by the var initialisation.

Why cant I add var in if statement

I'm trying to run a simple program to teach my friend to code:
var name = prompt("Whats your name");
if name = "Jason" {alert ("your name is Jason");
but for some reason it just wont let me ad the variable "name". What should I do?
I think you need
if (name === "Jason") { /*Do something */}
Rather than the single equals. Double/triple equals compares whereas single equals sets.

Javascript: find asterisk in database field

I am checking a stream of data in Pentaho Data Integration and am using some Javascript. Certain fields may have one asterisk as the value. So I have:
if (Workgroup = "*") {
summary_level = "A";
} else {
summary_level = "W";
}
All values are getting set to "A", even fields where the value is not "*". I have tried:
Workgroup = /\\*/
Workgroup = /\*/
I know I have to escape it, just not sure how I have supposed to write it as a regular expression.
You are assigning, not comparing. What you want is if(Workgroup == "*"), the double = means is equal to.
This is the reason why a few programmers write it the other way, if("*" = Workgroup) would result in an obvious error, you cant overwrite a constant string.

Javascript: Flexibility of function parameters?

The description of Javascript function parameters on W3Schools wasn't very clear, so I just want to clarify.
From my understanding, there isn't a type restriction; the "real value" of the parameters are passed into the method. Is there a way to pass objects or elements? Or is that what is meant by "real value"?
For example:
The function displayText meant to take input text and set a display to show a new word in the given input text, going to the next word every time it's called.
function displayText() {
var text = document.getElementById("words").value;
// Since text is initialized
// every time the method is called,
// it will always start at the beginning of the text area.
// Not sure how to fix this since making `text`
// a global variable doesn't work
var list = text.split(/[ \t\n]+/);
displayNext(list, "display");
}
There is a "helper" method, displayNext, which is supposed to shift to the next word in the list and sets the display to that word.
function displayNext(list, textboxID) {
document.getElementById(textboxID).innerHTML = list.shift();
}
This isn't working as it is intended. I'm fairly sure it's because I've mucked up something with the parameters, since displayNext sets innerHTML to null. list must have not passed properly. I'm not sure how to fix this.
I'm sure there's a more efficient way to do this, but this is a good opportunity to learn how Javascript parameters actually work, so I thought I'd ask.
JSFiddle
Based on the comments in your code, it sounds like you want displayText() to display the "next" word each time. To do that, you have to create some place to store some state about which word is the next one to display. As you have it now, you create a new array every time and always display the first word.
The simplest way is to create a variable outside your function in some lasting scope where you store the word number:
var wordNum = 0;
function displayText() {
var text = document.getElementById("words").value;
var list = text.split(/\s+/);
if (list.length !== 0) {
// make sure we aren't off the end of the list
wordNum = wordNum % list.length;
displayNext(list[wordNum++], "display");
}
}
function displayNext(text, textboxID) {
document.getElementById(textboxID).innerHTML = text;
}
For a lot more info about arguments to Javascript functions and even how you can detect what arguments were passed or overload arguments, see this answer: How to overload functions in javascript? and for more info about how arguments are passed: Javascript by reference vs. by value

How to make javascript write to itself, and then when that code is ran again say it's already been run and add to a counter

I'm somewhat new to javascript, but I had an idea, code where the user inputs code, and the machine remembers and it and assigns it to a random variable name, and spits out the things that happen, and the name of the variable so it can be called again.
Lets say I enter this:
var input1 = prompt("Hi how are you");
if(input1 = "good"){
alert("That's great!");
}else if(input1 = "bad"){
alert("I hope it perks up!");
}else{
alert("Input not recognized");
}
When he/she enters it it then assigns it to a variable first, so any code inside itself can't modify itself before that, so any code that modifies itself doing it won't have to worry, then it runs it. After it runs it displays the variable number so they can call it later.
One thing for the variable I might have to have it check to see if it already exists as a variable name, and if it does it recalculates a variable name.
So basically code that saves it to itself in a variable causing itself to grow.
Self-modifying code is generally not a good idea.
In this case, if all you want to do is remember something in a variable, one option is to use web storage, specifically local storage.
To get the value (with a default if none has ever been stored):
var value = JSON.parse(localStorage.getItem("value") || "0");
To save the value for next time:
localStorage.setItem("value", JSON.stringify(value));
localStorage is the browser-supplied object that manages local storage.
I'm using JSON because web storage only ever stores strings, so my general pattern is to store JSON text. In this specific case, for just a number, it's a bit overkill and you could just use parseInt or the unary + coercion trick:
// Loading
var value = +localStorage.getItem("value") || 0;
// Saving (will implicitly be coerced to a string)
localStorage.setItem("value", value);
I'm also using the curiously-powerful || operator (more about that on my blog)*.
More in the specification and on MDN.
Live Example on jsFiddle (Stack Snippets don't allow using web storage):
HTML:
<input type="button" value="Click Me">
JavaScript:
document.querySelector("input").addEventListener("click", function(e) {
var value = +localStorage.getItem("value") || 0;
++value;
alert("That was click #" + value + " on this browser.");
localStorage.setItem("value", value);
});

Categories

Resources